[Python-ideas] Unpacking a dict

Ethan Furman ethan at stoneleaf.us
Wed May 25 15:03:41 EDT 2016


On 05/25/2016 11:52 AM, Paul Moore wrote:
> On 25 May 2016 at 19:47, Ethan Furman wrote:
>> On 05/25/2016 11:42 AM, Steven D'Aprano wrote:
>>> On Wed, May 25, 2016 at 01:11:35PM +0000, Michael Selik wrote:

>>>>       py> mapping = {"a": 1, "b": 2, "c": 3}
>>>>       py> {"a": x, "b": y, "c": z} = mapping
>>>>       py> x, y, z
>>>>       (1, 2, 3)
>>>
>>>
>>> I think that is too verbose and visually baffling. I'd rather see
>>> something less general and (in my opinion) more useful:
>>>
>>> a, b, c = **mapping
>>>
>>> being equivalent to:
>>>
>>> a = mapping['a']
>>> b = mapping['b']
>>> c = mapping['c']
>>
>>
>> +1
>>
>> Simplest, easiest to grok, probably solves 95+% of the use-cases.
>
> OTOH, you could also do
>
> x = SimpleNamespace(**mapping)
>
> and use x.a, x.b, x.c.

Beside visual clarity, the other big reason for using local variables 
instead constant dict access is speed -- which you lose by using another 
object.

--
~Ethan~


More information about the Python-ideas mailing list