英文:
How to get a value from a dictionary which might be None in python
问题
There is a dictionary object named my_dic.
my_dic = {'name': 'tom'}
print(f"The name is {my_dic.get('name')}")
In case my_dic is None, there will be an expected exception as 'NoneType' object has no attribute 'get'.
How to make one line code to get None in case my_dic is None, otherwise return by get().
Thanks.
英文:
There is a dictionary object named my_dic.
my_dic = {'name': 'tom'}
print(f"The name is {my_dic.get('name')}")
In case my_dic is None, there will be an expected exception as 'NoneType' object has no attribute 'get'
.
How to make one line code to get None in case my_dic is None, otherwise return by get().
Thanks.
答案1
得分: 1
您可以使用条件表达式来处理 `my_dic` 为 `None` 的情况。
```python
>>> my_dic = None
>>> print(f"名字是 {my_dic.get('name') if my_dic else None}")
名字是 None
>>> print(f"名字是 {None if my_dic is None else my_dic.get('name')}")
名字是 None
<details>
<summary>英文:</summary>
You might use a conditional expression to handle the case where `my_dic` is `None`.
>>> my_dic = None
>>> print(f"The name is {my_dic.get('name') if my_dic else None}")
The name is None
>>> print(f"The name is {None if my_dic is None else my_dic.get('name')}")
The name is None
</details>
# 答案2
**得分**: 1
my_dic = {'name': 'tom'} # 返回 name
# my_dic = None # 如果 my_dic 为 None,则返回 None
print(f"The name is {my_dic.get('name')}" if my_dic is not None else None)
<details>
<summary>英文:</summary>
my_dic = {'name': 'tom'} # return name
# my_dic = None # return None if my_dic is None
print(f"The name is {my_dic.get('name')}" if my_dic is not None else None)
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论