I have the following snippet:
a, b = 1, 2
params = ['a', 'b']
res = {p: vars()[p] for p in params}
Which gives me KeyError: 'a' whereas the following code works fine:
a, b = 1, 2
params = ['a', 'b']
res = {}
for p in params:
    res[p] = vars()[p] 
What's the difference here?
vars() without any argument acts like locals() and since a dictionary comprehension has its own scope it has no variable named a or b.
You can use eval() here. Without any argument it will execute in LEGB manner, or specify globals() dict explicitly to eval:
>>> res = {p: eval(p) for p in params}
>>> res
{'a': 1, 'b': 2}
But then again the correct way will be to create a dictionary from the start if you want to access variables using their names.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With