我想做的事情是:
foo = {
'foo': 1,
'zip': 2,
'zam': 3,
'bar': 4
}
if ("foo", "bar") in foo:
#do stuff
我如何检查是否foo和酒吧都在dict foo?
我想做的事情是:
foo = {
'foo': 1,
'zip': 2,
'zam': 3,
'bar': 4
}
if ("foo", "bar") in foo:
#do stuff
我如何检查是否foo和酒吧都在dict foo?
当前回答
>>> if 'foo' in foo and 'bar' in foo:
... print 'yes'
...
yes
Jason,()在Python中不是必需的。
其他回答
你可以这样做:
>>> if all(k in foo for k in ("foo","bar")):
... print "They're there!"
...
They're there!
>>> if 'foo' in foo and 'bar' in foo:
... print 'yes'
...
yes
Jason,()在Python中不是必需的。
并不是说这不是你没有想过的事情,但我发现最简单的事情通常是最好的:
if ("foo" in foo) and ("bar" in foo):
# do stuff
这里有一个替代的解决方案,以防你想要得到不匹配的项目……
not_existing_keys = [item for item in ["foo","bar"] if item not in foo]
if not_existing_keys:
log.error('These items are missing', not_existing_keys)
检测是否所有键都在字典中的另一个选项:
dict_to_test = { ... } # dict
keys_sought = { "key_sought_1", "key_sought_2", "key_sought_3" } # set
if keys_sought & dict_to_test.keys() == keys_sought:
# True -- dict_to_test contains all keys in keys_sought
# code_here
pass