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

标签 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'

我怎样才能创建一个具有这样的理解力的字典?

最佳答案

字典理解有它的自己的命名空间,而那个命名空间中的locals() 没有a。从技术上讲,除了最外层可迭代对象的初始可迭代对象(此处 ["a"])之外的所有内容几乎都作为嵌套函数运行,最外层可迭代对象作为参数传入。

如果您改用 globals(),或者创建对 locals() 字典 外部 的字典理解,您的代码就可以工作:

l = locals()
print { key: l[key] for key in ["a"] }

演示:

>>> a = 1
>>> l = locals()
>>> { key: l[key] for key in ["a"] }
{'a': 1}
>>> { key: globals()[key] for key in ["a"] }
{'a': 1}

关于使用 locals() 的 Python 字典理解给出 KeyError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22485399/

相关文章:

python - 在字典理解语句中迭代

python - 以循环方式向下移动 Pandas 数据帧

python - 是否可以更新 Doc2Vec 矢量?

python - 从包含列表的元组列表中进行字典理解

java - 如何将 python dict 对象转换为 java 等效对象?

python - 字典理解索引错误

python - f.write 与打印 >> f

python - 如何将文件从谷歌云存储加载到谷歌云功能

python - 从 python 字典中打印列

python - 如何在 Python 中结合以下理解?