9

Is there a shorthand way of checking for keys in a dictionary?

Something that I can use instead of using multiple in and and operators - instead of the following:

('somekey' in d) and ('someotherkey' in d) and ('somekeyggg' in d)
3
  • What's wrong with this? It looks very clear and elegant. Commented Aug 19, 2011 at 22:44
  • It gets annoying if you have to do it for 8 or 9 keys. Commented Aug 19, 2011 at 22:45
  • Then consider showing that as the example. The three key version isn't bad, and doesn't demonstrate any real problem. Commented Aug 19, 2011 at 22:46

2 Answers 2

24
all( word in d for word in [ 'somekey', 'someotherkey', 'somekeyggg' ] )
Sign up to request clarification or add additional context in comments.

5 Comments

@Gareth: why did you add that split?
@reno sorry to pick nits, but I believe that would be a generator expression.
This should be changed back to its original form. No reason for the edit.
@Gareth: You can explain in your own answer why you think using a string and split() is better, but I see no reason to change the other answers to follow this approach.
@Marty: Not really a nit you're picking here: the generator expression short-circuits on the first word that's not in d. A list comprehension will create the entire list of boolean values before calling the all function. This is a really cool feature of using all() and any() with generator expressions.
5
set(['somekey', 'someotherkey', 'somekeyggg']).issubset(d)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.