我想做的事情是:
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', 'bar'} <= set(some_dict):
pass
这也比all(k in d…)解决方案性能更好。
其他回答
那么使用呢?
if reduce( (lambda x, y: x and foo.has_key(y) ), [ True, "foo", "bar"] ): # do stuff
if {"foo", "bar"} <= myDict.keys(): ...
如果你还在使用python2,你可以这样做
if {"foo", "bar"} <= myDict.viewkeys(): ...
如果你仍然使用非常老的Python <= 2.6,你可以在字典上调用set,但它会遍历整个字典来构建集合,这是很慢的:
if set(("foo", "bar")) <= set(myDict): ...
检查字典中是否存在所有键:
{'key_1', 'key_2', 'key_3'} <= set(my_dict)
检查字典中是否存在一个或多个键:
{'key_1', 'key_2', 'key_3'} & set(my_dict)
检测是否所有键都在字典中的另一个选项:
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
短而甜
{"key1", "key2"} <= {*dict_name}