我想做的事情是:
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?
当前回答
短而甜
{"key1", "key2"} <= {*dict_name}
其他回答
检查字典中是否存在所有键:
{'key_1', 'key_2', 'key_3'} <= set(my_dict)
检查字典中是否存在一个或多个键:
{'key_1', 'key_2', 'key_3'} & set(my_dict)
你不需要把左边包在一个集合里。你可以这样做:
if {'foo', 'bar'} <= set(some_dict):
pass
这也比all(k in d…)解决方案性能更好。
你可以这样做:
>>> if all(k in foo for k in ("foo","bar")):
... print "They're there!"
...
They're there!
对我来说,简单和容易与pydash裁判中间的无键
import pydash as _
_.get(d, 'key1.key2.key3.whatevermaybeNone.inthemiddle', default=None) )
在确定是否只有一些键匹配的情况下,这是有效的:
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