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?
try this
result:
Instead of elaborate lambda functions or dictionary comprehension, may as well use a built in library.
Here's another way to do it similarly to how a destructuring assignment works in JS:
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:
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.
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:
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: