使用locals()的Python词典理解给出KeyError [英] Python dictionary comprehension using locals() gives KeyError

查看:265
本文介绍了使用locals()的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"])的初始可迭代对象之外的所有东西,几乎都是作为嵌套函数运行的,最外面的可迭代对象作为参数传递.

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()或创建对dict理解的locals()词典的引用,您的代码将起作用:

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}

这篇关于使用locals()的Python词典理解给出KeyError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆