When should iteritems() be used instead of items()?

In Python 2.x – .items() returned a list of (key, value) pairs. In Python 3.x, .items() is now an itemview object, which behaves differently – so it has to be iterated over, or materialised… So, list(dict.items()) is required for what was dict.items() in Python 2.x.

Python 2.7 also has a bit of a back-port for key handling, in that you have viewkeys, viewitems and viewvalues methods, the most useful being viewkeys which behaves more like a set (which you’d expect from a dict).

Simple example:

common_keys = list(dict_a.viewkeys() & dict_b.viewkeys())

Will give you a list of the common keys, but again, in Python 3.x – just use .keys() instead.

Python 3.x has generally been made to be more “lazy” – i.e. map is now effectively itertools.imap, zip is itertools.izip, etc.

Leave a Comment