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?
Python is only able to "destructure" sequences, not dictionaries. So, to write what you want, you will have to map the needed entries to a proper sequence. As of myself, the closest match I could find is the (not very sexy):
This works with generators too:
Here is a full example:
Maybe you really want to do something like this?
Based on @ShawnFumo answer I came up with this:
(Notice the order of items in dict)
If you are afraid of the issues involved in the use of the locals dictionary and you prefer to follow your original strategy, Ordered Dictionaries from python 2.7 and 3.1 collections.OrderedDicts allows you to recover you dictionary items in the order in which they were first inserted
Well, if you want these in a class you can always do this:
I don't know whether it's good style, but
locals().update(params)
will do the trick. You then have
a
,b
and whatever was in yourparams
dict available as corresponding local variables.