6

There are several different ways to check if a Python dictionary contains a specific key, i.e.

d = {}

if key in d:

if d.contains(key):

if d.has_key(key):

it's silly for a language to allow you to do the same thing several different ways, UNLESS, each of the methods was doing something entirely different. Could someone please contrast the three techniques above, how are they different?

Mark Biek
  • 146,731
  • 54
  • 156
  • 201
vgoklani
  • 10,685
  • 16
  • 63
  • 101

4 Answers4

12

They're all the same and they're all around for historical reasons, but you should use key in d.

Ross Patterson
  • 5,702
  • 20
  • 38
7

Method #1 is the accepted way to do it. Method #2 doesn't actually exist, at least in any versions of Python that I'm aware of; I'd be interested to see where you found that. Method #3 used to be the accepted way, but is now deprecated.

So there really is just one way.

DNS
  • 37,249
  • 18
  • 95
  • 132
  • 1
    maybe he was thinking of `__contains__` – Gerrat Aug 29 '11 at 19:22
  • 4
    Just to piggback on this answer... if he *was* thinking of `__contains__` - the answer is that it is a special method used to implement `b in a`... the vm translates any `b in a` references into a call to `a.__contains__(b)` behinds the scenes, much like `a[b]` is translated to `a.__getitem__(b)`. The special `__xxx__` methods are how python provides a clean method-based implementation of all the syntactic sugar the language publically offers. – Eli Collins Aug 29 '11 at 19:44
5

d.__contains__(key) is what is used it key in d (since in operator calls __contains__ method of the dictionary)

has_key is deprecated and does the same as __contains__

ovgolovin
  • 13,063
  • 6
  • 47
  • 78
4
  • key in d is the accepted way to do it.

  • __contains__ is the ‘“magic” attribute’ (ref) that implements the above syntax. Most, if not all, special syntax is implemented via such methods. E.g., the with statement is implemented via __enter__ and __exit__. Such methods exist for allowing special functionality to be provided for user-defined classes.

  • the has_key method no longer exists in Python 3 and is deprecated in Python 2.

Neil G
  • 32,138
  • 39
  • 156
  • 257