[Python-ideas] Unpacking a dict

Michel Desmoulin desmoulinmichel at gmail.com
Wed May 25 13:49:57 EDT 2016


I'm currently working on a data export softare using 1000th of
OrderedDicts. Sometime I iterate, and sometime I get part of it.


Currently I have a wrapper doing:

x, y , z = d(data).unpack('x', 'y', 'z', default=None)

So I can see a use for it. And it's not the first time I wish I could do
this.

Although I think for a shortcut to lookup automatically the vars with
the same name as the dict keys by default would be nice:

{x, y, z} = data

Le 25/05/2016 17:18, Paul Moore a écrit :
> On 25 May 2016 at 14:11, Michael Selik <michael.selik at gmail.com> wrote:
>> Clojure also supports mapping destructuring. Let's add that to Python!
>>
>>     py> mapping = {"a": 1, "b": 2, "c": 3}
>>     py> {"a": x, "b": y, "c": z} = mapping
>>     py> x, y, z
>>     (1, 2, 3)
>>     py> {"a": x, "b": y} = mapping
>>     Traceback:
>>     ValueError: too many keys to unpack
>>
>>
>> This will be approximately as helpful as iterable unpacking was before PEP
>> 3132 (https://www.python.org/dev/peps/pep-3132/).
> 
> 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
> (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.
> 
> Paul
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/
> 


More information about the Python-ideas mailing list