isar
isar

Reputation: 1791

Splat Unpacking a Dictionary

I tried to unpack a list:

ls = [1, 2, 3]
a, *b = ls

Then, I tried to unpack a dictionary:

dc = {'x': 1, 'y': 2, 'z': 3}
a, **b = dc
# Out: SyntaxError

I was expecting this to work...

This is not a big deal since I can still get the keys (a, *b = dc), the values (a_val, *b_val = dc.values()) and zip them into a dictionary. But I'm curious: am I missing something here? Will this be possible in the future?

By the way, I'm using Python 3.6, where a dictionary is not yet guaranteed to be ordered but even using collection.OrderedDict the unpacking doesn't work.

Upvotes: 2

Views: 3450

Answers (1)

Adam Smith
Adam Smith

Reputation: 54213

The obvious problem is ordering. Since dictionaries are unordered, it's easy to produce values that introduce subtle bugs in code that seems like it should work.

dc = {'x': 1, 'y': 2, 'z': 3}
a, *b = dc
# `a` could be any of 'x', 'y', 'z'
a2, **b2 = dc
# `a2` could be any of {'x': 1}, {'y': 2}, {'z': 3}
# (though I believe it's constrained to be the same key as `a` above)

Upvotes: 3

Related Questions