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

Ben Finney ben+python at benfinney.id.au
Mon Jul 27 06:23:46 CEST 2015

Petr Viktorin <encukou at gmail.com> 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. Every time I
> do, it seems it's boilerplate; it looks a like a workaround rather
> than a preferred way of doing things.

I am sympathetic to this complaint. It does seem that mapping, for all
their “obvious first choice” as a data structure, are more cumbersome to
iterate through than other sequences.

I tend to write the above as::

    for (key, value) in a_dict.items():
        # ...

because it's easier to see that the items that come from the view are
themselves two-item tuples which are then unpacked.

> 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)

Hmm, that's a bit too easy to misread for my liking.

A colon in the middle of a line, without clear parenthesis syntax
nearby, looks too much like a single-line compound statement::

    if foo: bar
    while True: flonk
    for key: value in a_dict:

I would be only +0 on the above ‘for’ syntax, and would prefer that it
remains a SyntaxError.

Analogous to what I described above for the tuple unpacking, how about

    for {key: value} in a_dict:
        # ...

That makes the correspondence with a mapping much less ambiguous, and it
clearly marks the whole item which will be emitted by the iteration.

 \          “There's a certain part of the contented majority who love |
  `\            anybody who is worth a billion dollars.” —John Kenneth |
_o__)                                            Galbraith, 1992-05-23 |
Ben Finney

More information about the Python-ideas mailing list