Reputation: 21887
How can I check if a dictionary (actually dictionary-like object) has all of a given set of keys (plural)?
So far, I have used:
d = { 'a': 1, 'b': 2, 'c': 3 }
keys = ('a', 'b')
def has_keys(d, keys):
for key in keys:
if not key in d:
return False
return True
Is there a more elegant and Pythonic way of doing this?
Upvotes: 2
Views: 3097
Reputation: 34493
Use the builtin function all()
>>> d = { 'a': 1, 'b': 2, 'c': 3 }
>>> keys = ('a', 'b')
>>> all(elem in d for elem in keys)
True
>>> keys = ('a', 'b', 'd')
>>> all(elem in d for elem in keys)
False
Upvotes: 14
Reputation: 172408
You may also try like this:
>>> names = {
'a' : 11,
'b' : 10,
'c' : 14,
'd': 7
}
>>> keys = ('a', 'b')
>>> set(keys).issubset(names)
True
Upvotes: 2
Reputation: 1
You can just use keyword "in" ex: d = { 'a': 1, 'b': 2, 'c': 3 } if 'd' in d: print 'yes' else: print 'no'
Upvotes: -1