Advertisement
Advertisement


Should I use 'has_key()' or 'in' on Python dicts?


Question

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
2018/11/29
1
942
11/29/2018 6:37:23 AM

Accepted Answer

in is definitely more pythonic.

In fact has_key() was removed in Python 3.x.

2013/04/30
1335
4/30/2013 3:56:24 PM

in wins hands-down, not just in elegance (and not being deprecated;-) but also in performance, e.g.:

$ 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 is not always true, you'll notice that usually, in Python, the faster solution is more elegant and Pythonic; that's why -mtimeit is SO helpful -- it's not just about saving a hundred nanoseconds here and there!-)

2009/08/24

According to python docs:

has_key() is deprecated in favor of key in d.

2013/04/11

Use dict.has_key() if (and only if) your code is required to be runnable by Python versions earlier than 2.3 (when key in dict was introduced).

2012/01/18

There is one example where in actually kills your performance.

If you use in on a O(1) container that only implements __getitem__ and has_key() but not __contains__ you will turn an O(1) search into an O(N) search (as in falls back to a linear search via __getitem__).

Fix is obviously trivial:

def __contains__(self, x):
    return self.has_key(x)
2012/01/18

Solution to dict.has_key() is deprecated, use 'in' -- sublime text editor 3

Here I have taken an example of dictionary named 'ages' -

ages = {}

# Add a couple of names to the dictionary
ages['Sue'] = 23

ages['Peter'] = 19

ages['Andrew'] = 78

ages['Karren'] = 45

# use of 'in' in if condition instead of function_name.has_key(key-name).
if 'Sue' in ages:

    print "Sue is in the dictionary. She is", ages['Sue'], "years old"

else:

    print "Sue is not in the dictionary"
2016/05/11

Source: https://stackoverflow.com/questions/1323410
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]