Common Python Idioms

Steven D'Aprano steve at REMOVE.THIS.cybersource.com.au
Sat Dec 9 02:44:56 EST 2006


On Fri, 08 Dec 2006 17:42:56 +0100, Daniel Dittmar wrote:

> Marc 'BlackJack' Rintsch wrote:
>> If ``in`` shouldn't work with dictionaries, either `__contains__()` must
>> be implemented to throw an exception or dictionaries shouldn't be iterable.
> 
> I agree completely (in the sense that dictionaries shouldn't be iterable 
> directly).

Why on earth not???


> Probably even more strongly, at least every time I see some 
> code where someone iterates over the keys, only to use the key to look 
> up the value (instead if using iteritms).

Is there really that much difference between the two?

>>> D = dict(zip(xrange(10000), xrange(10000)))
>>> def d1(D):
...     for key in D:
...             value = D[key]
...
>>> def d2(D):
...     for key, value in D.iteritems():
...             pass
...
>>> timeit.Timer("d1(D)", "from __main__ import d1, d2, D").timeit(1000)
5.9806718826293945
>>> timeit.Timer("d2(D)", "from __main__ import d1, d2, D").timeit(1000)
4.7772250175476074

Using iteritems is slightly faster, and probably more Pythonic, but the
difference isn't so great to argue that "for key in dict" is always the
wrong thing to do.

One could argue until the cows come home whether "for x in dict" should
iterate over keys, values or key/value pairs, but it really doesn't
matter. All three possibilities are available, all three values are
useful, and having to copy the keys/values into a list in order to iterate
over them is just wasteful.


-- 
Steven.




More information about the Python-list mailing list