我想做的事情是:

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

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

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


当前回答

if {"foo", "bar"} <= myDict.keys(): ...

如果你还在使用python2,你可以这样做

if {"foo", "bar"} <= myDict.viewkeys(): ...

如果你仍然使用非常老的Python <= 2.6,你可以在字典上调用set,但它会遍历整个字典来构建集合,这是很慢的:

if set(("foo", "bar")) <= set(myDict): ...

其他回答

并不是说这不是你没有想过的事情,但我发现最简单的事情通常是最好的:

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

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

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

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

{'key_1', 'key_2', 'key_3'} & set(my_dict)

短而甜

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

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

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