在字典中使用eval
我想使用字典本身来评估字典键的值。例如:
dict_ = {'x': 1, 'y': 2, 'z':'x+y'}
dict_['z'] = eval(dict_['z'], dict_)
print(dict_)
当我这样做时,它在字典中包含了一堆不必要的东西。在上面的例子中,它打印:
{'x': 1, 'y': 2, 'z': 3, '__builtins__': bunch-of-unnecessary-stuff-too-long-to-include
Instead, in the above example I just want:
{'x': 1, 'y': 2, 'z': 3}
{'x': 1, 'y': 2, 'z': 3}
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_)
Prints: