我想做的事情是:

foo = {
    'foo': 1,
    'zip': 2,
    'zam': 3,
    'bar': 4
}

if ("foo", "bar") in foo:
    #do stuff

我如何检查是否foo和酒吧都在dict foo?


当前回答

对我来说,简单和容易与pydash裁判中间的无键

import pydash as _
_.get(d, 'key1.key2.key3.whatevermaybeNone.inthemiddle', default=None) )

其他回答

my_dict = {
    'name': 'Askavy',
    'country': 'India',
    'age': 30
}

if set(('name', 'country','age')).issubset(my_dict.keys()):
     print("All keys are present in the dictionary") 
else: 
    print("All keys are not present in  the dictionary") 

使用集:

if set(("foo", "bar")).issubset(foo):
    #do stuff

另外:

if set(("foo", "bar")) <= set(foo):
    #do stuff

你可以这样做:

>>> if all(k in foo for k in ("foo","bar")):
...     print "They're there!"
...
They're there!

那么使用呢?

 if reduce( (lambda x, y: x and foo.has_key(y) ), [ True, "foo", "bar"] ): # do stuff

检查字典中是否存在所有键:

{'key_1', 'key_2', 'key_3'} <= set(my_dict)

检查字典中是否存在一个或多个键:

{'key_1', 'key_2', 'key_3'} & set(my_dict)