Using 'in' with a Dict

Steven Bethard steven.bethard at gmail.com
Wed Feb 16 17:14:31 EST 2005


kowboy wrote:
> I posted too quickly. A little performance testing told me that has_key
> is somewhat slower than "in". I used a large number of string keys in
> my test.

See my other post, but the reason has_key is slower is almost certainly 
that it has to do a LOAD_ATTR:

$ python -m timeit -s "m = dict.fromkeys(xrange(100, 200))" "[i in m for 
i in xrange(300)]"
10000 loops, best of 3: 102 usec per loop

$ python -m timeit -s "m = dict.fromkeys(xrange(100, 200)); 
has_key=m.has_key" "[has_key(i) for i in xrange(300)]"
10000 loops, best of 3: 107 usec per loop

For this data at least, the difference is negligible.  (I actually found 
has_key to be faster in some other datasets.)

STeVe



More information about the Python-list mailing list