[Python-ideas] Dictionary destructing and unpacking.

Nick Humrich nick at humrich.us
Wed Jun 7 14:14:08 EDT 2017


In python, we have beautiful unpacking:
a, b, c = [1,2,3]

and even
a, b, *c = [1,2,3,4,5]

We also have dictionary destructing for purposes of keywords:
myfunc(**mydict)

You can currently unpack a dictionary, but its almost certainly not what
you would intend.
a, b, c = {'a': 1, 'c': 3, 'b': 2}.values()

In python 3.6+ this is better since the dictionary is insertion-ordered,
but is still not really what one would probably want.

It would be cool to have a syntax that would unpack the dictionary to
values based on the names of the variables. Something perhaps like:

a, b, c = **mydict

which would assign the values of the keys 'a', 'b', 'c' to the variables.
The problem with this approach is that it only works if the key is also a
valid variable name. Another syntax could potentially be used to specify
the keys you care about (and the order). Perhaps:

a, b, c = **mydict('a', 'b', 'c')

I dont really like that syntax, but it gives a good idea.

One way to possibly achieve this today without adding syntax support could
be simply adding a builtin method to the dict class:

a, b, c = mydict.unpack('a', 'b', 'c')


The real goal of this is to easily get multiple values from a dictionary.
The current ways of doing this are:

a, b, c, = mydict['a'], mydict['b'], mydict['c']
or
a = mydict['a']
b = mydict['b']
c = mydict['c']

The later seams to be more common. Both are overly verbose in my mind.

One thing to consider however is the getitem vs get behavior. mydict['a']
would raise a KeyError if 'a' wasnt in the dict, whereas mydict.get('a')
would return a "default" (None if not specified). Which behavior is chosen?
Maybe there is no clean solutions, but those are my thoughts. Anyone have
feedback/ideas on this?

Nick
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20170607/5fab297d/attachment.html>


More information about the Python-ideas mailing list