[Python-ideas] Unpacking a dict

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


On 05/25/2016 12:38 PM, Sven R. Kunze wrote:
> On 25.05.2016 20:42, Steven D'Aprano wrote:

>> There's no need to unpack the entire dict, you can grab only the keys
>> you need:
>>
>> width, height = **prefs
>>
>> # like
>> width = prefs['width']
>> height = prefs['height']
>
> That's not the same behavior as it is for tuple unpacking. As a new
> user, I would expect them to work the same way.
>
> If I want to dismiss the remainder of the dict, I'd rather consider an
> explicit approach:
>
> width, height = **prefs      # just those values
> width, height, *r = **prefs  # r captures the rest
>
>
> This gives me two benefits:
>
> 1) I can further work with r from which width and height are extracted
> 2) a convenient way of verifying that a dict only contains certain
> values and extracting those at the same time

Okay, those are good benefits.  +1

> Maybe, it's just me but I still tend to think that using unquoted
> strings should be reserved for attribute unpacking.

lists, tuples, and dicts are basic containers -- having syntax to 
unpacak them easily is a clear win;  attribute unpacking not so much:

--> some_long_object_name = MyClass(blah, blah)
--> s = some_long_object_name
--> s.name
some value
--> s.value
--> another value

which is sufficiently readable.

> One additional drawback of this solution is the fact that the "value"
> part of the colon is already taken. So, value matching like done in
> Erlang is not possible. OTOH, this applies to tuple unpacking in its
> current form as well

This is about unpacking, not matching.

--
~Ethan~



More information about the Python-ideas mailing list