Python字典理解给出了KeyError [英] Python dictionary comprehension gives KeyError
本文介绍了Python字典理解给出了KeyError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
>>> 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'
如何用这样的理解创建一个字典?
How can I create a dictionary with a comprehension like this?
推荐答案
一个dict的理解有其自己的命名空间和 locals()
在该命名空间中没有 a
。从技术上讲,除了最外层迭代(这里 [a]
)的初始迭代之外的所有内容都几乎作为嵌套函数运行,最外层的iterable作为参数传入。
A dict comprehension has its own namespace, and locals()
in that namespace has no a
. Technically speaking, everything but the initial iterable for the outermost iterable (here ["a"]
) is run almost as a nested function with the outermost iterable passed in as an argument.
如果您使用 globals()
,或者创建了对
Your code works if you used globals()
instead, or created a reference to the locals()
dictionary outside of the dict comprehension:
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}
这篇关于Python字典理解给出了KeyError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文