开发者

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

This question already has an answer here: Adding dynamic class to callers namespace (1 answer) Closed 9 years ago.

PHP has a function called extract() which takes an associative array as the argument a开发者_Go百科nd 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


Try:

    locals().update(my_dict)

EDIT:

gnibbler has made a very valid point that locals shouldn't be modified (check: http://docs.python.org/library/functions.html#locals). Still, Python docs doesn't say it's not safe, it only says that changes to locals may not affect values of variables. Before answering the question I tried in my Python's 2.6 IDLE that updating locals actually works, both in global scope and inside a function. That's why I'm not deleting my answer, but instead I'm adding a warning that it might work under certain (platform-specific?) circumstances, but it's not guaranteed.


Modifying locals() dict could have been a solution but docs say, http://docs.python.org/library/functions.html#

Note The contents of this dictionary should not be modified; changes may not affect the values of local and free variables used by the interpreter.

so the question is why you even need it? there may be better ways to achieve that whatever you are trying to achieve.

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜