[Python-ideas] Unpacking a dict

Eric V. Smith eric at trueblade.com
Wed May 25 16:08:10 EDT 2016


On 05/25/2016 02:12 PM, Paul Moore wrote:
> On 25 May 2016 at 17:08, Ethan Furman <ethan at stoneleaf.us> wrote:
>> 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.
> 
> Thanks. That's the sort of use case I thought might exist - and it
> sounds to me as if you'd get much more benefit from a syntax that
> allowed "partial" unpacking:
> 
> {"a": x, "b": y} = dict(a=1, b=2, c=3)
> 
> gives x=1, y=2 with no error.
> 
> I can't think of a good example where Michael's original proposal that
> this would give a ValueError would be a better approach.
> Paul

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

Eric.


More information about the Python-ideas mailing list