[英]How to assign value to the output of eval function in python
I tried to assign some value to output of the eval
function as below: 我尝试为eval
函数的输出分配一些值,如下所示:
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. 但是它不会改变d
字典。 I tried to eval
the whole assignment like this: 我试图像这样eval
整个任务:
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. 我也尝试过使用ast.literal_eval()
函数,并且所有结果都是相同的。 So, any idea how to do it?? 那么,任何想法该怎么做?
EDIT 1: 编辑1:
For clarification as @LennartRegebro requested for, I should say that I have some dictionaries with some specific key and value pairs. 为了按照@LennartRegebro的要求进行澄清,我应该说我有一些带有特定键和值对的字典。 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. 我想按eval
函数进行赋值,但我知道我做不到。
EDIT 2: 编辑2:
As @lejlot suggested, I used globals()
and added below lines to my code: 正如@lejlot所建议的,我使用了globals()
并在代码中添加了以下几行:
import re
pattern = re.compile(r'\["([A-Za-z0-9_\./\\-]+)"\]')
globals()[st1][pattern.findall(st2)[0]] = 15
Why don't you access your variables through globals()
(or locals()
) instead of eval
? 为什么不通过globals()
(或locals()
)而不是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']
Do a simple, 做一个简单的,
exec(st1 + st2 + '= 15')
eval
won't work. eval
将不起作用。 Use exec instead. 使用exec代替。 That too assignment should be done inside within the argument itself. 该分配也应在参数本身内部进行。
Though using exec
is a highly unrecommended practice. 虽然不建议使用exec
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.