Yan.Zero
Yan.Zero

Reputation: 449

Python:How to determine whether the dictionary contains multiple keys?

d={'a':1, 'b':2, ...}
if 'a' in d and 'b' in d and ...:
  pass

is there a simple way to determine multiple keys at once? something like:

if ['a', 'b'] in d:

Upvotes: 1

Views: 59

Answers (3)

user3951197
user3951197

Reputation: 1

len(d.keys()) will let you know how many keys are in your dictionary

Upvotes: -3

Robᵩ
Robᵩ

Reputation: 168626

d={'a':1, 'b':2, ...}
required_keys = set(('a', 'b', ...))

missing_keys = required_keys.difference(d.keys())
if missing_keys
  print "You are missing some keys: ", missing_keys
else:
  print "You have all of the required keys"

Upvotes: 2

BrenBarn
BrenBarn

Reputation: 251388

You can do

if all(key in d for key in ['a', 'b', 'c', ...]):

This may be longer than writing them out separately if you're only testing a couple, but as the list of keys to be tested grows longer, this way will be quicker, since you only have to add the key to the list and not write an additional in d and.

Upvotes: 4

Related Questions