What are the differences between dict.items() and dict.iteritems()? What are Iteritems () in Python?

764    Asked by EdythFerrill in Data Science , Asked on Jul 14, 2021
Are there any applicable differences between dict.items() and dict.iteritems()?

From the Python docs:

dict.items(): Return a copy of the dictionary’s list of (key, value) pairs.

dict.iteritems(): Return an iterator over the dictionary’s (key, value) pairs.

If I run the code below, each seems to return a reference to the same object. Are there any subtle differences that I am missing?

a={1:'one',2:'two',3:'three'}
print 'a.items():'
for k,v in a.items():
   if d[k] is v: print 'tthey are the same object'
   else: print 'tthey are different'
print 'a.iteritems():'   
for k,v in a.iteritems():
   if d[k] is v: print 'tthey are the same object'
   else: print 'tthey are different'   

Output-

a.items():
    they are the same object
    they are the same object
    they are the same object
a.iteritems():
    they are the same object
    they are the same object
    they are the same object

Answered by Robin Rose

dict.items() returns a list of tuples and it is time-consuming and memory exhausting whereas, dict.iteritems() is an iter-generator method which yields tuples and it is less time-consuming and less memory exhausting.

In Python 3, some changes were made and now, items() returns iterators and never builds a list fully. Moreover, in this version iteritems() was removed since items() performed the same function like viewitems() in Python 2.7.

What are Iteritems () in Python?

iteritems(): returns an iterator of the dictionary's list in the form of (key, value) tuple pairs. which is a (Python v2. x) version and got omitted in (Python v3. x) version.



Your Answer

Interviews

Parent Categories