tags:

views:

1206

answers:

6

Hi,

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
+5  A: 

My $0.02: the more Pythonic answer would be to use in.

Matt Ball
+47  A: 

in is definitely more pythonic, in fact has_key() was removed in python 3.x: http://docs.python.org/3.1/whatsnew/3.0.html#builtins

tonfa
thanks (added some text to avoid the 15 chars limitation ;))
igorgue
@igorgue: Add spaces. They count, but don't show up in the final comment.
nosklo
awesome
igorgue
As an addition, in Python 3, to check for the existence in values, instead of the keys, try >>> 1 in d.values()
Selinap
yeah, you can use it with lists too... "in" is pretty smart
igorgue
+9  A: 

According to python docs:

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

Nadia Alramli
+25  A: 

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

Alex Martelli
thanks a lot, good to know, now I'm changing my code to use 'in' instead of has_key() ;)
igorgue
+3  A: 

has_key is a dictionary method, but in will work on any collection, and even when __contains__ is missing, in will use any other method to iterate the collection to find out.

kaizer.se
And does also work on iterators "x in xrange(90, 200) <=> 90 <= x < 200"
kaizer.se
+3  A: 

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

John Machin