如果键在字典中有虚假值,则获取默认值

Get default value if key has falsy value in dict

我在 python 工作,并且在我的代码中使用了 dict

如果给定 key 不存在,或者如果 key 存在并且它具有 falsy 值,我总是需要 default 值。

例如

x = {'a': 'test', 'b': False, 'c': None, 'd': ''}
print x.get('a', [])
test
print x.get('b', []) # Need [] as False is falsy value in python
False 
print x.get('e', []) # This will work fine, because `e` is not valid key
None
print x.get('c', []) 
None
print x.get('c', []) or [] # This gives output which I want

不是检查 or 操作中的 Falsy 值,有没有任何 pythonic 方法来获取我的默认值?

使用 orreturn 你的默认值是 Pythonic。我不确定您是否会得到更 可读性 的解决方法。

关于在 docs 中使用 or

This is a short-circuit operator, so it only evaluates the second argument if the first one is False.

您还必须考虑到必须先访问该值,然后才能将其计算为 FalsyTruthy

这是一个丑陋的技巧:

from collections import defaultdict

x = {'a': 'test', 'b': False, 'c': None, 'd': ''}
d = defaultdict(lambda : [], dict((k, v) if v is not None else (k, []) for k, v in x.items()))
print(d['a'])
# test
print(d['b'])
# False
print(d['e'])
# []
print(d['c']) 
# []