rvighne
rvighne

Reputation: 21887

Check if dictionary has multiple keys

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

Answers (3)

Sukrit Kalra
Sukrit Kalra

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

Rahul Tripathi
Rahul Tripathi

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

user3866989
user3866989

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

Related Questions