我想做的事情是:

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

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

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


当前回答

短而甜

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

其他回答

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

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

我认为这是最聪明和最精辟的。

{'key1','key2'} <= my_dict.keys()

你也可以使用. is子集()

>>> {"key1", "key2"}.issubset({"key1":1, "key2":2, "key3": 3})
True
>>> {"key4", "key2"}.issubset({"key1":1, "key2":2, "key3": 3})
False
>>>
>>> if 'foo' in foo and 'bar' in foo:
...     print 'yes'
... 
yes

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

短而甜

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