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

Ron Adam ron3200 at gmail.com
Wed Jul 29 19:09:10 CEST 2015

On 07/29/2015 05:10 AM, Nick Coghlan wrote:
> 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:
> https://docs.python.org/3/library/stdtypes.html#dict.update
> 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}

I'm still wondering how it would work underneath and what other things it 

      kv = "red":6         # What would this do?

      k:v = ("red", 6)     # Would this work too?

      k, v = "red":6       # Or this?

Currently __contains__ on dictionaries only checks the keys.  So can this 
be made to work?

      k:v in D            # Test for key:value pair.


      D[k] == v

I wonder if k:v was to create an key_value object. This isn't that 
different than an operator/object that consumes other objects.

        bool = key:value(dict)   # KeyValue(key, value)(dict)

Or it could work like slice objects.

        def __contains__(self, other):
            if isinstance(other, KeyValue):

Or maybe have it as a special case on for loops only, but is that special 
case special enough?

> 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
> type.

I'm  -0.1, but only because I think it could create confusing cases like 
... if this works, then why can't this... kind of things.


More information about the Python-ideas mailing list