The Python Oracle

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

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------

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

--

Chapters
00:00 Should I Use 'Has_key()' Or 'In' On Python Dicts?
00:18 Accepted Answer Score 1626
00:31 Answer 2 Score 118
00:40 Answer 3 Score 275
01:10 Answer 4 Score 48
01:23 Thank you

--

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

--

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