How to assign value to the output of eval function in python -
i tried assign value output of eval
function below:
d = {"a": 10} st1 = 'd' st2 = '["a"]' eval(st1 + st2) = 15
i got error:
file "<stdin>", line 1 syntaxerror: can't assign function call
i tried this:
x = eval(st1 + st2) x = 15
but doesn't change d
dictionary. tried eval
whole assignment this:
eval(st1 + st2 + ' = 15')
but got error:
traceback (most recent call last): file "<stdin>", line 1, in <module> file "<string>", line 1 d["a"] = 15 ^ syntaxerror: invalid syntax
i have tried use ast.literal_eval()
function , results same. so, idea how it??
edit 1:
for clarification @lennartregebro requested for, should have dictionaries specific key , value pairs. have text file user , of these values defined there , should change basic dictionaries values these user defined ones. have parser parses text file , each change, gives me tuple containing dictionary name, key , value; strings. wanted assignments eval
function, understood can't.
edit 2:
as @lejlot suggested, used globals()
, added below lines code:
import re pattern = re.compile(r'\["([a-za-z0-9_\./\\-]+)"\]') globals()[st1][pattern.findall(st2)[0]] = 15
why don't access variables through globals()
(or locals()
) instead of eval
?
d={'a':10} globals()['d']['a']=15 print d['a']
in particular case
d={'a':10} s1='d' s2='a' globals()[s1][s2]=15 print d['a']
Comments
Post a Comment