Creating or assigning variables from a dictionary in Python

You can use the locals() function to access the local symbol table and update that table:

>>> mydict = {'raw': 'data', 'code': 500}
>>> locals().update(mydict)
>>> raw
'data'
>>> code
500

Modifying the symbol table that way is quite unusual, though, and probably not the way to go. Maybe you need to change your design so you can use the mydict dictionary instead of actual variables.


Horribly late to the game, but I needed exactly this, and my solution was:

mydict = {'raw':'data', 'code': 500}
raw, code = [mydict.get(k) for k in ['raw','code']]

That way it's explicit for reading and there's no potential clobbering of locals() (which is a magic that I'd rather avoid).


OK php brothers so here is a bad news, python can't create variables from out of space... like php can: ${$var} . To use local() is a very bad idea, because you'll have tons of problems with debugging, and there some locals already defined in there.. so it's really bad thing to do...

You can't create this programmatically like php does. I think it's called non-explicity, and this is one python general: You ALWAYS know variable name. This kind of stuff just a suicide in some cases, you need to write by hand tons of vars... Mostly i was unhappy because of things like XML parsing, but it appears that there are method how to convert python dictionary into class, I was told about this yesterday but still haven't checked how it works ( something like here )