Are there any applicable differences between dict.items() and dict.iteritems()?
From the Python docs:
dict.items()
: Return a
dict.items()
return list of tuples, and dict.iteritems()
return iterator object of tuple in dictionary as (key,value)
. The tuples are the same, but container is different.
dict.items()
basically copies all dictionary into list. Try using following code to compare the execution times of the dict.items()
and dict.iteritems()
. You will see the difference.
import timeit
d = {i:i*2 for i in xrange(10000000)}
start = timeit.default_timer() #more memory intensive
for key,value in d.items():
tmp = key + value #do something like print
t1 = timeit.default_timer() - start
start = timeit.default_timer()
for key,value in d.iteritems(): #less memory intensive
tmp = key + value
t2 = timeit.default_timer() - start
Output in my machine:
Time with d.items(): 9.04773592949
Time with d.iteritems(): 2.17707300186
This clearly shows that dictionary.iteritems()
is much more efficient.