python – How to test if a dictionary contains a specific key?

The Question :

310 people think this question is useful

What’s the cleanest way to test if a dictionary contains a key?

x = {'a' : 1, 'b' : 2}
if (x.contains_key('a')):
    ....

The Question Comments :
  • The tutorial is your friend.
  • @Steven – I believe duplicates are helpful, because they make this question easier to find. I did search before I posted, and didn’t find what I’m looking for.
  • @ripper234: This closed question will indeed make it easier for future searches to find the answered question, but that doesn’t make the question all that valuable in and of itself.
  • @Steven – “all that valuable” – valuable enough not to get -1 votes, even if not valuable enough for +1. That’s just IMHO of course, you’re free to vote as you wish 🙂
  • @StevenRumbalski “you didn’t search hard enough” — why do you want to make people search harder? I vote for easier searching over harder searching every time.

The Answer 1

576 people think this answer is useful
'a' in x

and a quick search reveals some nice information about it: http://docs.python.org/3/tutorial/datastructures.html#dictionaries

Tags:

Add a Comment