我想做的事情是:

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:
...     print 'yes'
... 
yes

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

>>> ok
{'five': '5', 'two': '2', 'one': '1'}

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

这似乎有用

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

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

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

>>> {"key1", "key2"}.issubset({"key1":1, "key2":2, "key3": 3})
True
>>> {"key4", "key2"}.issubset({"key1":1, "key2":2, "key3": 3})
False
>>>

短而甜

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