我想做的事情是:
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?
当前回答
检测是否所有键都在字典中的另一个选项:
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
其他回答
在确定是否只有一些键匹配的情况下,这是有效的:
any_keys_i_seek = ["key1", "key2", "key3"]
if set(my_dict).intersection(any_keys_i_seek):
# code_here
pass
还有另一个选项,如果只有一些键匹配:
any_keys_i_seek = ["key1", "key2", "key3"]
if any_keys_i_seek & my_dict.keys():
# code_here
pass
你不需要把左边包在一个集合里。你可以这样做:
if {'foo', 'bar'} <= set(some_dict):
pass
这也比all(k in d…)解决方案性能更好。
检查字典中是否存在所有键:
{'key_1', 'key_2', 'key_3'} <= set(my_dict)
检查字典中是否存在一个或多个键:
{'key_1', 'key_2', 'key_3'} & set(my_dict)
这里有一个替代的解决方案,以防你想要得到不匹配的项目……
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)
这应该可以工作:
if all(key in foo for key in ["foo","bar"]):
# do stuff
pass
提示:
在all()中使用方括号来创建一个列表推导式:
if all([key in foo for key in ["foo","bar"]]):
不仅是不必要的,而且是非常有害的,因为它们阻碍了all()的正常短路行为。