for key, value in dict.<func>() - how to get? (which func)
Diez B. Roggisch
deets at nospam.web.de
Tue Aug 11 18:23:39 EDT 2009
dmitrey schrieb:
> Yes, thank you, items() is the correct approach, on the other hand I
> have already get rid of the cycle.
Most certainly items() is *not* the correct approach if you are
concerned so much with performance, because items() first creates a list
of key/value-pairs, where iteritems() will be an effective iterator.
so if you are (IMHO wrongly) concerned about performance of an O(1)
lookup, items() certainly costs more.
And the following program proves it:
import time
d = dict(zip(xrange(100000), xrange(100000)))
start = time.time()
for loops in xrange(100):
for key in d:
value = d[key]
print "lookup: ", time.time() - start
start = time.time()
for loops in xrange(100):
for key, value in d.items():
value = d[key]
print "items: ", time.time() - start
start = time.time()
for loops in xrange(100):
for key, value in d.iteritems():
value = d[key]
print "items: ", time.time() - start
The result on my machine is:
deets$ python /tmp/test.py
lookup: 2.78633999825
items: 7.42830610275
items: 3.69960308075
So actually your condemed approach seems to be the fastest, where the
items() call by far is the slowest approch.
"In the face of ambiguity, refuse the temptation to guess."
Diez
More information about the Python-list
mailing list