[Python-ideas] Syntax for key-value iteration over mappings

Stephen J. Turnbull stephen at xemacs.org
Mon Jul 27 12:21:25 CEST 2015

Petr Viktorin writes:

 > Currently, the way to iterate over keys and values of a mapping
 > is to call items() and iterate over the resulting view::
 >     for key, value in a_dict.items():
 >         print(key, value)
 > I believe that looping over all the data in a dict is a very imporant
 > operation, and I find myself writing this quite often.

Sure, but the obvious syntax:

    for key, value in a_dict:

is already taken: it unpacks the key if it happens to be a tuple.
I've always idly wondered why iteration over a mapping was taken to be
an iteration over keys rather than over items.  Idling just a little
bit faster, I wonder if this isn't a throwback to the days when sets
were emulated by dictionaries with constant value (eg, None).  I'm
hard put to think of the last time I wanted to actually iterate over
keys, doing something *other* than extracting the value.

However, given that the choice was made to iterate over keys rather
than items, it doesn't bother me to put in explicit calls to .items or
.values where needed.

 > In dict comprehensions and literals, key-value pairs are separated by
 > colons. How about allowing that in for loops as well?
 >     for key: value in a_dict:
 >         print(key, value)

This screams SyntaxError to me.  Sure, I can figure out what's meant,
but the cognitive burden would be large every time I saw it.

More generally, YMMV but I don't see any real point in adding syntax
for this.


More information about the Python-ideas mailing list