Creating or assigning variables from a dictionary in Python

holms picture holms · Dec 5, 2010 · Viewed 18.8k times · Source

I tried to ask a question normally once in here but nobody understands what I want to ask. So I've found example in PHP.

// $_POST = array('address' => '123', 'name' => 'John Doe');
extract($_POST);
echo $address;
echo $name

is there's a function like extract() in PYTHON?????

So the same goes to dictionary:

mydict = {'raw':'data', 'code': 500}
// some magic to extract raw and code as vars
print raw 

p.s. why I want to do this: when you're in class method, it's damned hard to have 6 manipulation with strings in join() and format() when string is self.data['raw']['code'] (assume it's dict in dict in here)

Answer

Frédéric Hamidi picture Frédéric Hamidi · Dec 5, 2010

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.