[Tutor] Why isn't iteritems() working when items() does?

Steven D'Aprano steve at pearwood.info
Sun Apr 28 04:49:50 CEST 2013


On 28/04/13 12:21, Jim Mooney wrote:
> #Changing a dictionary into a 2-tuple list with the items method
> works, as per the
> #first example. But using iteritems returns an error - using Py33

Dicts no longer have three distinct methods for retrieving keys and values, as they did in Python 2.x. In Python 2, you had:


keys, iterkeys, viewkeys
values, itervalues, viewvalues
items, iteritems, viewitems

In Python 3, those nine methods have been reduced to three:

keys
values
items


Why did Python 2 have so many methods?

Way back in the dawn of time, Python dicts only had three such methods, keys, values and items. All three returned a list of the keys etc. The disadvantage of returning a list is that for large dicts, this can be very expensive, especially if you only need to look at one key at a time. And so were born the iter* versions, which lazily produced the keys etc. one at a time without needing to construct a full list first.

A few versions on, and dict *views* were invented. Views are described in the PEP (Python Enhancement Proposal) that introduced them:

http://www.python.org/dev/peps/pep-3106/

Come Python 3, and backward compatibility is allowed to be broken. So the dict methods that return lists and iterators were dropped, and the viewkeys, viewvalues and viewitems methods were renamed to just play old keys, values and items.

And that is where we stand today.


By the way, you can see what methods and attributes are available on an object using the dir() built-in function, and read some documentation about it using the help() function. At the interactive interpreter:

dir({}) will give a list of dict methods.

help({}) will drop you into the help system.



-- 
Steven


More information about the Tutor mailing list