Question

I tried to assign some value to output of the eval function as below:

d = {"a": 10}
st1 = 'd'
st2 = '["a"]'
eval(st1 + st2) = 15

I got this error:

File "<stdin>", line 1
SyntaxError: can't assign to function call

I also tried this:

x = eval(st1 + st2)
x = 15

But it doesn't change the d dictionary. I tried to eval the whole assignment like this:

eval(st1 + st2 + ' = 15')

But I got this error:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1
  d["a"] = 15
         ^
SyntaxError: invalid syntax

I also have tried to use ast.literal_eval() function and all the results were the same. So, any idea how to do it??

EDIT 1:

For clarification as @LennartRegebro requested for, I should say that I have some dictionaries with some specific key and value pairs. I have a text file which I get from user and some of these values are defined there and I should change basic dictionaries values to these user defined ones. I have parser which parses the text file and for each change, it gives me a tuple containing dictionary name, key and value; all are strings. I wanted to do the assignments by eval function, which I understood that I can't.

EDIT 2:

As @lejlot suggested, I used globals() and added below lines to my code:

import re
pattern = re.compile(r'\["([A-Za-z0-9_\./\\-]+)"\]')
globals()[st1][pattern.findall(st2)[0]] = 15
Was it helpful?

Solution

Why don't you access your variables through globals() (or locals()) instead of eval?

d={'a':10}
globals()['d']['a']=15
print d['a']

in your particular case

d={'a':10}
s1='d'
s2='a'
globals()[s1][s2]=15
print d['a']

OTHER TIPS

Do a simple,

exec(st1 + st2 + '= 15')

eval won't work. Use exec instead. That too assignment should be done inside within the argument itself.

Though using exec is a highly unrecommended practice.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top