我想做的事情是:

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) )

其他回答

这里有一个替代的解决方案,以防你想要得到不匹配的项目……

not_existing_keys = [item for item in ["foo","bar"] if item not in foo]
if not_existing_keys:
  log.error('These items are missing', not_existing_keys)

这应该可以工作:

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()的正常短路行为。

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

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

你可以这样做:

>>> if all(k in foo for k in ("foo","bar")):
...     print "They're there!"
...
They're there!
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")