我想做的事情是:

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…)解决方案性能更好。

其他回答

如果你想:

还可以获取键的值 多查字典

然后:

from operator import itemgetter
foo = {'foo':1,'zip':2,'zam':3,'bar':4}
keys = ("foo","bar") 
getter = itemgetter(*keys) # returns all values
try:
    values = getter(foo)
except KeyError:
    # not both keys exist
    pass
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 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): ...
>>> ok
{'five': '5', 'two': '2', 'one': '1'}

>>> if ('two' and 'one' and 'five') in ok:
...   print "cool"
... 
cool

这似乎有用