I want to evaluate the value of a dict key, using the dict itself. For example:
JavaScript
x
4
1
dict_ = {'x': 1, 'y': 2, 'z':'x+y'}
2
dict_['z'] = eval(dict_['z'], dict_)
3
print(dict_)
4
When I do this it includes a bunch of unnecessary stuff in the dict. In the above example it prints:
JavaScript
1
2
1
{'x': 1, 'y': 2, 'z': 3, '__builtins__': bunch-of-unnecessary-stuff-too-long-to-include
2
Instead, in the above example I just want:
JavaScript
1
2
1
{'x': 1, 'y': 2, 'z': 3}
2
How to resolve this issue? Thank you!
Advertisement
Answer
Pass a copy of dict to eval()
:
JavaScript
1
5
1
dict_ = {"x": 1, "y": 2, "z": "x+y"}
2
3
dict_["z"] = eval(dict_["z"], dict_.copy())
4
print(dict_)
5
Prints:
JavaScript
1
2
1
{'x': 1, 'y': 2, 'z': 3}
2