如何从一个可能为None的字典中获取值在Python中

huangapple go评论56阅读模式
英文:

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 = {&#39;name&#39;: &#39;tom&#39;} # return name 
    # my_dic = None # return None if my_dic is None
    print(f&quot;The name is {my_dic.get(&#39;name&#39;)}&quot; if my_dic is not None else None)

</details>



huangapple
  • 本文由 发表于 2023年7月18日 12:15:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/76709493.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定