[Python-ideas] Unpacking a dict

Ethan Furman ethan at stoneleaf.us
Wed May 25 16:14:37 EDT 2016


On 05/25/2016 01:08 PM, Eric V. Smith wrote:

> How is this an improvement over:
>
> def extract(mapping, *keys):
>      return [mapping[key] for key in keys]
>
> mapping = {'a': 1, 'b': 2, 'c': 3}
>
> x, y = extract(mapping, 'a', 'b')
> print(x, y)
> 1, 2

Let's pretend you wrote:

   a, b = extract(mapping, 'a', 'b')

since that's the way I would almost always be using it.

The proposal is this:

   a, b = **mapping

The advantages:

- much more readable
- less duplication

Less duplication might not seem like that big a deal, but it's one of 
the motivators behind decorations and in-place operators, which are both 
wins.

--
~Ethan~


More information about the Python-ideas mailing list