views:

85

answers:

4

Hi,

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?

Thanks

+1  A: 

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 your params dict available as corresponding local variables.

jellybean
Please note this may be a big security problem if the 'params' dictionary is user-provided in any way and not properly filtered.
Jacek Konieczny
To quote http://docs.python.org/library/functions.html#locals: *Note: The contents of this dictionary should not be modified; changes may not affect the values of local and free variables used by the interpreter.*
THC4k
Learned the lesson. Thx, guys.
jellybean
Doh! I really wanted the answer to be something like this...
Stephen
+1  A: 

Well, if you want these in a class you can always do this:

class AttributeDict(dict):
    def __init__(self, *args, **kwargs):
        super(AttributeDict, self).__init__(*args, **kwargs)
        self.__dict__.update(self)

d = AttributeDict(a=1, b=2)
abyx
Nice. Thanks, but seems like a way to change the call syntax from d['a'] to d.a? And perhaps adding methods that have implicitly access to these parameters...
Stephen
+2  A: 

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

joaquin
Thanks... still on Python 2.5/2.6...
Stephen
@Stephen you are lucky because OrderedDicts have been ported to python 2.7 from python 3.1
joaquin
I look forward to it...! Thought that was always a sticking point for Python for me (that ordered dictionaries didn't come loaded with the other batteries)
Stephen
+2  A: 

Maybe you really want to do something like this?

def some_func(a, b):
  print a,b

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

some_func(**params) # equiv to some_func(a=1, b=2)
THC4k
Thanks, but not that... I'm destructuring within a function
Stephen