使用locals()的Python字典理解给出了KeyError

J V*_*J V 4 python dictionary dictionary-comprehension

>>> a = 1
>>> print { key: locals()[key] for key in ["a"] }
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in <dictcomp>
KeyError: 'a'
Run Code Online (Sandbox Code Playgroud)

如何创建一个像这样理解的字典?

Mar*_*ers 12

字典理解有自己的命名空间,并且locals()该命名空间没有a.从技术上讲,除了最外层迭代(此处["a"])的初始迭代之外的所有内容几乎都作为嵌套函数运行,最外面的iterable作为参数传入.

如果您使用了代码globals(),或者在字典理解之外创建了对locals()字典的引用,则代码可以正常工作:

l = locals()
print { key: l[key] for key in ["a"] }
Run Code Online (Sandbox Code Playgroud)

演示:

>>> a = 1
>>> l = locals()
>>> { key: l[key] for key in ["a"] }
{'a': 1}
>>> { key: globals()[key] for key in ["a"] }
{'a': 1}
Run Code Online (Sandbox Code Playgroud)