在字典中使用 eval

tik*_*kka 0 python dictionary eval

我想使用字典本身来评估字典键的值。例如:

dict_ = {'x': 1, 'y': 2, 'z':'x+y'}
dict_['z'] = eval(dict_['z'], dict_)
print(dict_)
Run Code Online (Sandbox Code Playgroud)

当我这样做时,它在字典中包含了一堆不必要的东西。在上面的例子中,它打印:

{'x': 1, 'y': 2, 'z': 3, '__builtins__': bunch-of-unnecessary-stuff-too-long-to-include
Run Code Online (Sandbox Code Playgroud)

Instead, in the above example I just want:

{'x': 1, 'y': 2, 'z': 3}
Run Code Online (Sandbox Code Playgroud)

How to resolve this issue? Thank you!

And*_*ely 5

Pass a copy of dict to eval():

dict_ = {"x": 1, "y": 2, "z": "x+y"}

dict_["z"] = eval(dict_["z"], dict_.copy())
print(dict_)
Run Code Online (Sandbox Code Playgroud)

Prints:

{'x': 1, 'y': 2, 'z': 3}
Run Code Online (Sandbox Code Playgroud)

  • 当您将 `_dict` 作为第二个参数传递给 `eval()` 时,它将成为 `eval()` 内的全局命名空间。Python 控制着全局命名空间,并用它做一些你意想不到的事情。 (2认同)