Computer >> Computer tutorials >  >> Programming >> Python

What is the difference between dict.items() and dict.iteritems() in Python?


In Python 2.x, both methods are available, but in Python 3.x iteritems() is deprecated.

As far as Python 2.x is concerned, items() method of dictionary object returns list of two element tuples, each tuple containing key and value. On the other hand iteritems() is a generator which provides an iterator for items in a dictionary

>>> d = {'1': 1, '2': 2, '3': 3}
>>> d.items() 
[(1, 1), (2, 2), (3, 3)]
>>> for i in d.iteritems(): 
   print i 

('1', 1)
('2', 2)
('3', 3)

In Python 3, items() method behaves like iteritems() in Python 2

>>> d={'1': 1, '2': 2, '3': 3}
>>> d1.items()
dict_items([('1', 1), ('2', 2), ('3', 3)])
>>> d.items()
dict_items([('1', 1), ('2', 2), ('3', 3)])
>>> for i in d.items():
   print (i)

('1', 1)
('2', 2)
('3', 3)