Coder Perfect

On Python dicts, should I use ‘has key()’ or ‘in’?

Problem

I wonder what is better to do:

d = {'a': 1, 'b': 2}
'a' in d
True

or:

d = {'a': 1, 'b': 2}
d.has_key('a')
True

Asked by igorgue

Solution #1

It has a more pythonic feel to it.

In Python 3.x, the has key() function was deprecated.

Answered by tonfa

Solution #2

Not only in terms of elegance (and not being mocked;-), but also in terms of performance, for example:

$ python -mtimeit -s'd=dict.fromkeys(range(99))' '12 in d'
10000000 loops, best of 3: 0.0983 usec per loop
$ python -mtimeit -s'd=dict.fromkeys(range(99))' 'd.has_key(12)'
1000000 loops, best of 3: 0.21 usec per loop

While the following observation isn’t always true, you’ll note that the faster approach is usually more elegant and Pythonic; this is why -mtimeit is so useful — it’s not just about saving a few hundred nanoseconds here and there!-)

Answered by Alex Martelli

Solution #3

According to the Python documentation:

Answered by Nadia Alramli

Solution #4

If (and only if) your code has to execute on Python versions prior to 2.3, use dict.has key() (when key in dict was introduced).

Answered by John Machin

Solution #5

There is one instance where it has a negative impact on your performance.

If you use it on an O(1) container that only implements __getitem__ and has key() but not __contains__, an O(1) search will become an O(N) search (due to the fact that __getitem__ falls back to a linear search).

The solution is self-evident:

def __contains__(self, x):
    return self.has_key(x)

Answered by schlenk

Post is based on https://stackoverflow.com/questions/1323410/should-i-use-has-key-or-in-on-python-dicts