我想做的事情是:
foo = {
'foo': 1,
'zip': 2,
'zam': 3,
'bar': 4
}
if ("foo", "bar") in foo:
#do stuff
我如何检查是否foo和酒吧都在dict foo?
我想做的事情是:
foo = {
'foo': 1,
'zip': 2,
'zam': 3,
'bar': 4
}
if ("foo", "bar") in foo:
#do stuff
我如何检查是否foo和酒吧都在dict foo?
当前回答
你可以这样做:
>>> if all(k in foo for k in ("foo","bar")):
... print "They're there!"
...
They're there!
其他回答
在确定是否只有一些键匹配的情况下,这是有效的:
any_keys_i_seek = ["key1", "key2", "key3"]
if set(my_dict).intersection(any_keys_i_seek):
# code_here
pass
还有另一个选项,如果只有一些键匹配:
any_keys_i_seek = ["key1", "key2", "key3"]
if any_keys_i_seek & my_dict.keys():
# code_here
pass
如果你想:
还可以获取键的值 多查字典
然后:
from operator import itemgetter
foo = {'foo':1,'zip':2,'zam':3,'bar':4}
keys = ("foo","bar")
getter = itemgetter(*keys) # returns all values
try:
values = getter(foo)
except KeyError:
# not both keys exist
pass
>>> if 'foo' in foo and 'bar' in foo:
... print 'yes'
...
yes
Jason,()在Python中不是必需的。
短而甜
{"key1", "key2"} <= {*dict_name}
那么使用呢?
if reduce( (lambda x, y: x and foo.has_key(y) ), [ True, "foo", "bar"] ): # do stuff