我想做的事情是:

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

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

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


当前回答

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

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)

其他回答

虽然我喜欢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')),因为它更短。然而,这并不是那么容易理解的,我认为大括号太容易被混淆为字典。

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

短而甜

{"key1", "key2"} <= {*dict_name}

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

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