首页 > 解决方案 > Python 字典 - 如果 dict 值为 None,则 dict.get() 返回值

问题描述

None如果 dict 中的值使用类似的方法,有没有办法返回另一个值get

IE。

my_dict = {
 "my_key": None
}

我想要实现的类似于这个逻辑:

my_variable = my_dict.get("my_key", "Not None")
# After executing the line above the value of my_variable should be "Not None"

我知道get检查字典中是否存在密钥,如果密钥不存在,则返回第二个参数。有没有类似的方法或单线来做到这一点?

标签: pythondictionary

解决方案


唯一的方法是在检索值后检查

my_dict = {'my_key': None}
my_value = "None Value" if my_dict.get('my_key', "") is None else my_dict.get('my_key', "")

print(my_value)
# None Value

推荐阅读