The Python Oracle

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

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game Looping

--

Chapters
00:00 Question
00:24 Accepted answer (Score 1574)
00:40 Answer 2 (Score 272)
01:13 Answer 3 (Score 113)
01:27 Answer 4 (Score 46)
01:46 Thank you

--

Full question
https://stackoverflow.com/questions/1323...

Accepted answer links:
[has_key()]: http://docs.python.org/3.1/whatsnew/3.0....

Answer 3 links:
[docs]: http://docs.python.org/library/stdtypes....

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #dictionary

#avk47



ACCEPTED ANSWER

Score 1626


in is definitely more pythonic.

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




ANSWER 2

Score 275


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!-)




ANSWER 3

Score 118


According to python docs:

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




ANSWER 4

Score 48


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).