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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With