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

Petr Viktorin encukou at gmail.com
Tue Jul 28 19:39:55 CEST 2015

On Mon, Jul 27, 2015 at 4:12 AM, Steven D'Aprano <steve at pearwood.info> wrote:
> On Sun, Jul 26, 2015 at 06:09:17PM +0200, Petr Viktorin wrote:
>> Hello,
>> 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;
> What part looks like boilerplate? The "for"? The "key,value"? The "in"?
> The "a_dict"? If none of them are boilerplate, why would ".items()" be
> boilerplate?

Yes, the .items().

I got the courage to post here after a EuroPython talk, "Through the
lens of Haskell", where we discussed that unlike other languages,
where libraries can define new operators or even syntax for common
operations, Python tends to standardize syntax for common operations,
and ends up with a few pieces of syntax and a few common interfaces
that similar objects then implement. And so, Python ends up using
punctuation for common cases, like:
    value = mapping[key]
and methods for
    value = mapping.get(key, default)
The first is the "obvious way" to do it; I can grok its meaning
quickly just from the "shape" of the line. At a glance I can tell that
"mapping" needs to be some container.
In the second case something extra is going on, and parsing the word
"get" needs a bit of extra cognitive overhead to alert me to this. I
read that "mapping" needs to be an object with the "get" method.

Similarly, when I read:
    for key, value in mapping.items()
it looks like something "extra" is going on: it's a loop over tuples
that contain the key and value. On the other hand, the proposed
    for key: value in mapping:
would read, to me, as looping over all data in a dict.

Of course there is a cost: new punctuation does need to be learned.
Expressions like "{x: y for x in ...}" or "head, *tail = seq" or even
"p = []" aren't obvious until you go through the Python 101.
My assertion was that key-value looping is common enough (i.e. used in
almost every nontrivial program), and the proposed syntax is close
enough to similar uses of the colon (as a key-value separator), to
justify every Python developer learning it.
Now I know several core devs disagree with that, which means Python
will probably be better without it. Thanks for the discussion,

More information about the Python-ideas mailing list