【问题标题】:Python dictionary - dict.get() return value if dict value is NonePython 字典 - 如果 dict 值为 None,则 dict.get() 返回值
【发布时间】:2020-09-29 13:58:28
【问题描述】:

如果字典中的值为None,是否可以使用类似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 检查字典中是否存在键,如果键不存在,则返回第二个参数。有没有类似的方法或单线来做到这一点?

【问题讨论】:

  • 如果my_key 不存在,None"Not None",你想要什么?
  • 我的主脚本默认每个键为None,因此始终假定该键始终存在于字典中。
  • 那为什么不直接默认你真正想要的值呢?
  • 当前映射到None 的每个键是否需要不同的real 值?不将密钥添加到dict 并让get 执行其设计目的似乎更简单。
  • 约定是只存储映射到可用值的键。

标签: python dictionary


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2011-09-02
    • 1970-01-01
    • 2012-03-06
    • 2019-08-24
    • 1970-01-01
    • 2017-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多