Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to extract a dict in Python into the local namespace? [duplicate]

PHP has a function called extract() which takes an associative array as the argument and creates local variables out of the keys whose values are assigned to the key's values. Is there a way to do this in Python? A quick google search didn't immediately show me how. I suspect there's a way with exec() but it'd be nice if there were some function to do it for me.

like image 782
Kevin Avatar asked Feb 23 '10 08:02

Kevin


1 Answers

Since it is not safe to modify the dict that locals() returns

>>> d={'a':6, 'b':"hello", 'c':set()}
>>> exec '\n'.join("%s=%r"%i for i in d.items())
>>> a
6
>>> b
'hello'
>>> c
set([])

But using exec like this is ugly. You should redesign so you don't need to dynamically add to your local namespace

Edit: See Mike's reservations about using repr in the comments.

>>> d={'a':6, 'b':"hello", 'c':set()}
>>> exec '\n'.join("%s=d['%s']"%(k,k) for k in d)
>>> id(d['c'])
3079176684L
>>> id(c)
3079176684L
like image 53
John La Rooy Avatar answered Oct 26 '22 16:10

John La Rooy