Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: issue when using vars() dictionary

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?

like image 850
Ulysses Avatar asked Jun 24 '15 07:06

Ulysses


1 Answers

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.

like image 90
Ashwini Chaudhary Avatar answered Oct 14 '22 17:10

Ashwini Chaudhary