The following code doesn't work, I assume because the locals()
variable inside the comprehension will refer to the nested block where comprehension is evaluated:
def f():
a = 1
b = 2
list_ = ['a', 'b']
dict_ = {x: locals()[x] for x in list_}
KeyError: 'a'
I could use globals()
instead, and it seems to work, but that may come with some additional problems (e.g., if there was a variable from a surrounding scope that happens to have the same name).
Is there anything that would make the dictionary using the variables precisely in the scope of function f
?
Note: I am doing this because I have many variables that I'd like to put in a dictionary later, but don't want to complicate the code by writing dict_['a']
instead of a
in the meantime.