Destructuring-bind dictionary contents

2020-01-30 12:08发布

I am trying to 'destructure' a dictionary and associate values with variables names after its keys. Something like

params = {'a':1,'b':2}
a,b = params.values()

But since dictionaries are not ordered, there is no guarantee that params.values() will return values in the order of (a, b). Is there a nice way to do this?

10条回答
We Are One
2楼-- · 2020-01-30 12:38

try this

d = {'a':'Apple', 'b':'Banana','c':'Carrot'}
a,b,c = [d[k] for k in ('a', 'b','c')]

result:

a == 'Apple'
b == 'Banana'
c == 'Carrot'
查看更多
爷的心禁止访问
3楼-- · 2020-01-30 12:39
from operator import itemgetter

params = {'a': 1, 'b': 2}

a, b = itemgetter('a', 'b')(params)

Instead of elaborate lambda functions or dictionary comprehension, may as well use a built in library.

查看更多
相关推荐>>
4楼-- · 2020-01-30 12:41

Here's another way to do it similarly to how a destructuring assignment works in JS:

params = {'b': 2, 'a': 1}
a, b, rest = (lambda a, b, **rest: (a, b, rest))(**params)

What we did was to unpack the params dictionary into key values (using **) (like in Jochen's answer), then we've taken those values in the lambda signature and assigned them according to the key name - and here's a bonus - we also get a dictionary of whatever is not in the lambda's signature so if you had:

params = {'b': 2, 'a': 1, 'c': 3}
a, b, rest = (lambda a, b, **rest: (a, b, rest))(**params)

After the lambda has been applied, the rest variable will now contain: {'c': 3}

Useful for omitting unneeded keys from a dictionary.

Hope this helps.

查看更多
Fickle 薄情
5楼-- · 2020-01-30 12:42

One way to do this with less repetition than Jochen's suggestion is with a helper function. This gives the flexibility to list your variable names in any order and only destructure a subset of what is in the dict:

pluck = lambda dict, *args: (dict[arg] for arg in args)

things = {'blah': 'bleh', 'foo': 'bar'}
foo, blah = pluck(things, 'foo', 'blah')

Also, instead of joaquin's OrderedDict you could sort the keys and get the values. The only catches are you need to specify your variable names in alphabetical order and destructure everything in the dict:

sorted_vals = lambda dict: (t[1] for t in sorted(dict.items()))

things = {'foo': 'bar', 'blah': 'bleh'}
blah, foo = sorted_vals(things)
查看更多
登录 后发表回答