我想做的事情是:

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

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

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


当前回答

你可以这样做:

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

其他回答

>>> if 'foo' in foo and 'bar' in foo:
...     print 'yes'
... 
yes

Jason,()在Python中不是必需的。

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

这似乎有用

检测是否所有键都在字典中的另一个选项:

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

虽然我喜欢Alex Martelli的回答,但在我看来,它并不像python。也就是说,我认为Pythonic的一个重要部分是易于理解。有了这个目标,<=就不容易理解了。

虽然它有更多的字符,但使用Karl Voigtland的答案所建议的is子集()更容易理解。由于该方法可以使用字典作为参数,一个简短的、可理解的解决方案是:

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

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

我想使用{'foo', 'bar'}来代替set(('foo', 'bar')),因为它更短。然而,这并不是那么容易理解的,我认为大括号太容易被混淆为字典。