[Python-ideas] Unpacking a dict

Paul Moore p.f.moore at gmail.com
Wed May 25 11:18:52 EDT 2016


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


More information about the Python-ideas mailing list