Common Python Idioms

Fredrik Lundh fredrik at pythonware.com
Fri Dec 8 12:02:42 EST 2006


Daniel Dittmar wrote:

> I agree completely (in the sense that dictionaries shouldn't be iterable 
> directly). 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).

so?  that's the original Python way of doing things, and is both very 
readable and surprisingly efficient:

$ timeit -s "d = vars()" "for k in d: v = d[k]"
1000000 loops, best of 3: 0.472 usec per loop

$ timeit -s "d = vars()" "for k, v in d.iteritems(): pass"
1000000 loops, best of 3: 0.663 usec per loop

</F>




More information about the Python-list mailing list