[Python-ideas] Unpacking a dict

Random832 random832 at fastmail.com
Wed May 25 10:40:32 EDT 2016



On Wed, May 25, 2016, at 09:11, Michael Selik wrote:
> Python's iterable unpacking is what Lispers might call a destructuring
> bind.
> 
>     py> iterable = 1, 2, 3, 4, 5
>     py> a, b, *rest = iterable
>     py> a, b, rest
>     (1, 2, (3, 4, 5))
> 
> 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

How is this better than:
>>> mapping = {"a": 1, "b": 2, "c": 3}
>>> x, y, z = mapping[k] for k in ("a", "b", "c")


More information about the Python-ideas mailing list