Python dictionary comprehension using locals() gives KeyError

后端 未结 2 950
渐次进展
渐次进展 2020-12-02 02:22
>>> a = 1
>>> print { key: locals()[key] for key in [\"a\"] }
Traceback (most recent call last):
  File \"\", line 1, in 

        
相关标签:
2条回答
  • 2020-12-02 02:56

    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}
    
    0 讨论(0)
  • 2020-12-02 03:08

    You can try using globals() instead:

    print {key : globals()[key] for key in ["a"]}
    

    since a is not defined in the scope of the dict comprehension (as @MartijnPieters said).

    0 讨论(0)
提交回复
热议问题