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!
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)
| 归档时间: |
|
| 查看次数: |
43 次 |
| 最近记录: |