[Python-ideas] Unpacking a dict

Michael Selik michael.selik at gmail.com
Wed May 25 20:29:09 EDT 2016

On Wed, May 25, 2016 at 7:41 PM Ethan Furman <ethan at stoneleaf.us> wrote:

>    a, b = mapping
>    a, b, **_ = mapping  # when you don't care about the rest

I'd grudgingly accept this as a second-best syntax. It doesn't support keys
that aren't strs of valid identifiers, but I suppose ``def foo(**kwargs)``
doesn't either. I frequently have keys that are strs with punctuation, keys
that are tuples of ints, etc. Being restricted to identifiers feels cramped.

Also, I wonder if the implementation will be more difficult. In tuple
unpacking, it's the LHS that provides the semantic meaning. The RHS is just
duck-typed. What's the appropriate error message if you meant to do dict
unpacking and didn't have a mapping on the RHS?

    py> a, b = 42
    TypeError: 'int' object is not iterable
    py> {'a': x, 'b': y} = 42
    TypeError: 'int' object is not subscriptable

I think that most Pythonistas would say:
>    a, b = 1, 2  # look ma!  no round brackets!

You need brackets for nested/recursive destructuring.

    py> a, b, (c, d) = 1, 2, (3, 4)
    py> {'a': x, 'b': {'c': y, 'd': z} = {'a': 1, 'b': {'c': 2, 'd': 3}}

matching syntax is out-of-scope for an
> unpacking proposal.  At most, it should be a "let's not paint ourselves
> into a corner" type of concern -- and I must admit I don't see why
>    a, b, c = some_dict
> rules out
>   {'x': a, 'y':b} = some_dict
> as a pattern-matching construct.

Yep. I just want to look ahead a bit. While you're considering dict
unpacking syntax options, keep in mind that tuple matching will need to
parallel dict matching. Also, our future selves will want one-way-to-do-it
when considering matching syntaxes.

    py> a, b, c, 0 = 1, 2, 3, 4
    ValueError: index 3 does not match value 0
    py> {'x': a, 'y': 0} = {'x': 1, 'y': 2}
    ValueError: key 'y' does not match value 0

> On Wed, May 25, 2016 at 11:18 AM Paul Moore wrote:
> >> get a set of elements and *ignore* the rest:
> Since you've repeated yourself, I will too.  ;)

I figured repetition was more clear than "see above". :-)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20160526/ff992f81/attachment-0001.html>

More information about the Python-ideas mailing list