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

Nick Coghlan ncoghlan at gmail.com
Wed Jul 29 11:10:34 CEST 2015

On 29 July 2015 at 16:22, Pierre Quentel <pierre.quentel at gmail.com> wrote:
> If the proposal was accepted for "for k:v in iterable" then I suppose that
> "if k:v in iterable" would also be valid, meaning that for a dict, there is
> a pair (k, v) such that _dict[k] = v, and for a list that there is an index
> k such that _list[k] = v.
> for k:v in iterable:
>     assert k:v in iterable

This actually made me think of the quirky signatures of the dict
constructor and dict.update, where it's possible to pass in either a
mapping *or* an iterable of two-tuples:

If we went with the assumption that this syntax, if added, used those
semantics, then you could reliably build (assuming hashable values) a
reverse lookup table as:

    reverse_lookup = {v:k for k:v in data_source}

At the moment, you have to restrict your input to mappings specifically:

    reverse_lookup = {v:k for k,v in data_source.items()}

Or an iterable of 2-tuples:

    reverse_lookup = {v:k for k,v in data_source}

Or use duck-typing:

    if hasattr(data_source, "items"):
        data_source = data_source.items()
    reverse_lookup = {v:k for k,v in data_source}

I'd still be -0 on such a proposal with dict.update iteration
semantics (as much as I think it's neat, I don't think the practical
benefit is there to justify it), but it does have the virtue of
extracting a particular iteration pattern from an existing builtin


Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia

More information about the Python-ideas mailing list