我想做的事情是:

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):
    # do stuff
>>> ok
{'five': '5', 'two': '2', 'one': '1'}

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

这似乎有用

这应该可以工作:

if all(key in foo for key in ["foo","bar"]):
    # do stuff
    pass

提示:

在all()中使用方括号来创建一个列表推导式:

if all([key in foo for key in ["foo","bar"]]):

不仅是不必要的,而且是非常有害的,因为它们阻碍了all()的正常短路行为。

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

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

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

{'key_1', 'key_2', 'key_3'} & set(my_dict)
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")