Differences between dict.items() and dict.iteritems() in Python

Here we will see the basic differences between dict.items() and dict.iteritems() in Python.

dict.items() and dict.iteritems() are almost same except for some differences. dict.iteritems() is present only in Python version 2.x whereas dict.items() is used in Python 3.x only. You can not use iteritems() method in Python 3.x version.

dict.items(): returns a list of tuple whereas dict.iteritems() returns an an iterator over dictionary’s (key, value) pairs.

dict.items(): return a copy of list of dictionary’s (key, value) tuple pair.

dict = {'a':1, 'b':2,'c':3,'d':4}
print(dict.items())

Output for the above code will be:

[('a',1), ('c':3), ('b':2), ('d':4)]

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

dict = {'a':1, 'b':2,'c':3,'d':4} 
print(dict.iteritems())

Output: <dictionary-itemiterator object at 0x7f99e623f2e890>

dict = {'a':1, 'b':2,'c':3,'d':4}
for i in dict.iteritems():
    print(i)

Output for the above code will be:

('a': 1)
('c': 3)
('b': 2)
('d': 4)

Note :- Above examples are for Python version 2.x as iteritems() won’t work with Python 3.x version Python’s 3.x doesn’t support iteritems()  method.

For Python 3.x:-

dict = {'a':1, 'b':2,'c':3,'d':4}
print(dict.items())

Output for the above code will be:

dict_items([('a', 1), ('b', 2), ('c', 3), ('d', 4)])

But if we try to run .iteritems() in Python version 3.x we will encounter an error because iteritems() method no longers works with Python 3.x version.
While iterating through the dictionary the key and corresponding value can be obtained at the same time.

dict = {'a':1, 'b':2,'c':3,'d':4}
for key, values in dict.items():
    print(key, values)

Output for the above code will be:

a 1
b 2
c 3
d 4

Originally dict.items() return a copy of a list of dictionary’s (key, value) tuple pair that could take a lot of memory space whereas dict.iteritems () returns an iterator over the dictionary’s (key, value) pairs. Now with Python’s newer version items() now returns iterators and a list is never fully built and iteritem() method is also gone.

Also read:

Leave a Reply

Your email address will not be published. Required fields are marked *