我想做的事情是:
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?
当前回答
>>> ok
{'five': '5', 'two': '2', 'one': '1'}
>>> if ('two' and 'one' and 'five') in ok:
... print "cool"
...
cool
这似乎有用
其他回答
如果你想:
还可以获取键的值 多查字典
然后:
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 all(k in foo for k in ("foo","bar")):
... print "They're there!"
...
They're there!
我认为这是最聪明和最精辟的。
{'key1','key2'} <= my_dict.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")
检查字典中是否存在所有键:
{'key_1', 'key_2', 'key_3'} <= set(my_dict)
检查字典中是否存在一个或多个键:
{'key_1', 'key_2', 'key_3'} & set(my_dict)