Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Destructuring-bind dictionary contents

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?

like image 586
hatmatrix Avatar asked Jun 02 '10 06:06

hatmatrix


2 Answers

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.

like image 82
Zachary822 Avatar answered Oct 07 '22 19:10

Zachary822


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) 
like image 34
ShawnFumo Avatar answered Oct 07 '22 21:10

ShawnFumo