Is it legitimate to use items() instead of iteritems() in all places? Why was iteritems() removed from Python 3? Seems like a terrific and useful method. What’s the reasoning behind it?
Edit: To clarify, I want to know what is the correct idiom for iterating over a dictionary in a generator-like way (one item at a time, not all into memory) in a way that is compatible with both Python 2 and Python 3?
In Python 2.x –
.items()returned a list of (key, value) pairs. In Python 3.x,.items()is now anitemviewobject, which behaves differently – so it has to be iterated over, or materialised… So,list(dict.items())is required for what wasdict.items()in Python 2.x.Python 2.7 also has a bit of a back-port for key handling, in that you have
viewkeys,viewitemsandviewvaluesmethods, the most useful beingviewkeyswhich behaves more like aset(which you’d expect from adict).Simple example:
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.
mapis now effectivelyitertools.imap,zipisitertools.izip, etc.