[Python-ideas] Unpacking a dict

Ethan Furman ethan at stoneleaf.us
Wed May 25 12:08:45 EDT 2016


On 05/25/2016 08:18 AM, Paul Moore wrote:

> Neither this, nor the **rest extension you proposed, does what I think
> would be the most common requirement - get a set of elements and
> *ignore* the rest:
>
>--> mapping = {"a": 1, "b": 2, "c": 3}
>--> {"a": x, "b": y} = mapping
>--> # Note no error!
>--> x, y  # z discarded, should be NameError
> (1, 2)
>
> I'd still like to see some real-world use cases though - there are
> lots of options as the above example demonstrates, and nothing to
> guide us in deciding which would be the most useful one to choose.

Here's a real-world use-case:  The main software app I support passes a 
`values` dict around like the plague.  When doing interesting stuff I 
often unpack some of the values into local variables as that reads 
better, types better, and makes it easier to reason about the code (it's 
on 2.7 so for that I'll have to use Random's  example).

So for me, unpacking a dict with friendly syntax would be useful, and 
unpacking four or five keys from a 20-element dict will be far more 
useful than having to unpack them all.

--
~Ethan~



More information about the Python-ideas mailing list