Is there a way to extract a dict in Python into a local namespace?

PHP has an extract () function that takes an associative array as an argument and creates local variables from the keys whose values ​​are assigned to the key's values. Is there a way to do this in Python? A quick Google search did not immediately show me how to do this. I suspect there is a way with exec (), but it would be nice if I had some kind of function.

+6
python dictionary php
source share
4 answers

Since it is not safe to change 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 must redesign, so you do not need to dynamically add to the local namespace

Edit: See Mike on how to use reprint in 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 
+5
source share

Try:

  locals().update(my_dict) 

EDIT:

gnibbler made a very correct point that locals should not be changed (check: http://docs.python.org/library/functions.html#locals ). However, Python docs do not say that it is unsafe, it says that changes in locales may not affect the values ​​of variables. Before answering the question that I tried in my Python 2.6 IDLE, that updating locales really works, both in the global scope and inside the function. Therefore, I do not delete my answer, but instead add a warning that may work in certain (platform-specific?) Circumstances, but this is not guaranteed.

+3
source share

I found a similar question that was answered on SO. The accepted answer suggests translating your own extract for python.

-one
source share

Modifying locals () dict could be a solution, but according to docs, http://docs.python.org/library/functions.html#

Note. The contents of this dictionary should not be changed; changes may not affect the values ​​of the free variables used by the translator.

so the question is, why do you need this? there may be better ways to achieve what you are trying to achieve.

Also, why can't you directly access the dict or assign them to variables?

-one
source share

All Articles