Kev*_*vin 6 php python dictionary
PHP有一个名为extract()的函数,它将一个关联数组作为参数,并从其值分配给键值的键中创建局部变量.有没有办法在Python中执行此操作?快速的谷歌搜索没有立即告诉我如何.我怀疑exec()有一种方法,但是如果有一些函数可以帮我做的话会很好.
因为修改locals()返回的dict 是不安全的
>>> d={'a':6, 'b':"hello", 'c':set()}
>>> exec '\n'.join("%s=%r"%i for i in d.items())
>>> a
6
>>> b
'hello'
>>> c
set([])
Run Code Online (Sandbox Code Playgroud)
但是使用这样的exec很难看.您应该重新设计,这样您就不需要动态添加到本地命名空间
编辑:请参阅Mike对评论中使用repr的保留意见.
>>> 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
Run Code Online (Sandbox Code Playgroud)