[Python-ideas] Dictionary destructing and unpacking.

MRAB python at mrabarnett.plus.com
Thu Jun 8 16:02:40 EDT 2017


On 2017-06-08 20:16, Nick Badger wrote:
> Well, it's not deliberately not destructive, but I'd be more in favor of 
> dict unpacking-assignment if it were spelled more like this:
> 
>      >>> foo = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
>      >>> {'a': bar, 'b': baz, **rest} = foo
>      >>> bar
>      1
>      >>> baz
>      2
>      >>> rest
>      {'c': 3, 'd': 4}
>      >>> foo
>      {'a': 1, 'b': 2, 'c': 3, 'd': 4}
> 
> That also takes care of the ordering issue, and any ambiguity about "am 
> I unpacking the keys, the values, or both?", at the cost of a bit more 
> typing. However, I'm a bit on the fence about this syntax as well: it's 
> pretty easily confused with dictionary creation. Maybe the same thing 
> but without the brackets?
> 
[snip]

Maybe the braces could be doubled-up:

 >>> foo = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
 >>> {{a, b, **rest}} = foo
 >>> a
1
 >>> b
2
 >>> rest
{'c': 3, 'd': 4}

It could also be used on the RHS to pack:

 >>> a = 1
 >>> b = 2
 >>> c = 3
 >>> d = 4
 >>> foo = {{a, b, c, d}}
 >>> foo
{'a': 1, 'b': 2, 'c': 3, 'd': 4}


More information about the Python-ideas mailing list