Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
+1 vote
3 views
in Python by (1.6k points)

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

3 Answers

0 votes
by (10.9k points)

dict.items() returns a list of tuples and it is time-consuming and memory exhausting whereas, dict.iteritems() is an iter-generator method which yield 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.

If you wish to know what is python visit this python tutorial and python interview questions.

0 votes
by (20.3k points)

Method dict.items() returns a list of 2-tuples i.e. ([(key, value), (key, value), ...]), whereas dict.iteritems() is a generator that yields 2-tuples. 

In this, the former takes more space and time initially, but accessing each element is fast, whereas the second takes less space and time initially, but a bit more time in generating each element.

0 votes
by (106k points)

You can use the below-mentioned code:

>>> d={1:'one',2:'two',3:'three'}

>>> type(d.items()) 

<type 'list'> 

>>> type(d.iteritems()) 

<type 'dictionary-itemiterator'>

Related questions

+1 vote
1 answer
0 votes
1 answer
asked Oct 10, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer
0 votes
1 answer
asked Oct 11, 2019 in Python by Sammy (47.6k points)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...