[Python-3000] Default dict iterator should have been iteritems()

Noam Raphael noamraph at gmail.com
Tue Sep 4 10:49:53 CEST 2007


Just a thought that came to me after writing a code that deals quite a
lot with dicts:

The default dict iterator should in principle be iteritems(), and not

This is probably just theoritical, since it will break a lot of code
and not gain a lot, but it may be remembered when someone decides to
write a new language...

The reasoning is simple: Iteration over an object usually gets all the
data it contains. A dict can be seen as an unordered collection of
tuples (key, value), indexed by key. So, iteration over a dict should
yield those tuples.

For this reason, I think that "for key, value in dict.iteritems()" is
more common than "for key in dict" - When iterating over a dict, you
are usually interested in both the key and the value.

Another point: if the default dict iterator were iteritems(), the dict
copy constructor would not have been a special case - dict(x) always
gets an iterable over tuples and produces a new dict. Currently, if
you want to produce a dict from a UserDict, for example, you must call

As I see it, the only reason for the current status is the desire to
make "x in dict" equivalent to "dict.has_key(x)", since has_key is a
common operation and "x in" is shorter. But actually "dict.has_key(x)"
explains exactly what's intended, while "x in dict" isn't really clear
(for newbies, that is): do you ask whether x is in dict.keys(), or in
dict.values(), or in dict.items()?

Of course, if dict's default iterator were iteritems(), "x in dict"
should have meant "x in dict.items()", which is very easy to

What do you think?


More information about the Python-3000 mailing list