373

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

x = {'a' : 1, 'b' : 2}
if (x.contains_key('a')):
    ....
Samuel Liew
  • 76,741
  • 107
  • 159
  • 260
ripper234
  • 222,824
  • 274
  • 634
  • 905
  • 5
    The [tutorial](http://docs.python.org/tutorial/datastructures.html#dictionaries) is your friend. – Björn Pollex Mar 15 '11 at 13:59
  • -1 due to duplicate question. – Steven Rumbalski Mar 15 '11 at 14:33
  • 14
    @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 Mar 15 '11 at 15:09
  • 5
    @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 Rumbalski Mar 15 '11 at 15:21
  • 2
    @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 :) – ripper234 Mar 15 '11 at 15:36
  • @ripper234: My ratio of up votes to down votes is currently 194 to 10. You didn't search hard enough, hence the -1. – Steven Rumbalski Mar 15 '11 at 15:44
  • 14
    @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. – tadasajon Feb 12 '14 at 23:19
  • 1
    @JonCrowell: Enter the title of this question into Google and you will find that most of the top hits address his question. That's why I downvoted it. 3 other people agreed while 26 disagreed and gave an upvote. My opinion does not always fit in with the majority, but I'm not the only voter. The system works. If you disagree with my votes, just vote the opposite. – Steven Rumbalski Feb 12 '14 at 23:30

1 Answers1

691
'a' in x

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

Matt
  • 27,170
  • 6
  • 80
  • 74
cobbal
  • 69,903
  • 20
  • 143
  • 156