Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating or assigning variables from a dictionary

I tried to ask this question once before, but nobody understood 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 a dict in a dict).

like image 497
holms Avatar asked Dec 05 '10 07:12

holms


3 Answers

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.

like image 181
Frédéric Hamidi Avatar answered Sep 26 '22 14:09

Frédéric Hamidi


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).

like image 40
cybertoast Avatar answered Sep 23 '22 14:09

cybertoast


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 )

like image 28
holms Avatar answered Sep 25 '22 14:09

holms