Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

>>> 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
692 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.

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"] }

Demo:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...