tikka
tikka

Reputation: 577

Using eval within a dict

I want to evaluate the value of a dict key, using the dict itself. For example:

dict_ = {'x': 1, 'y': 2, 'z':'x+y'}
dict_['z'] = eval(dict_['z'], dict_)
print(dict_)

When I do this it includes a bunch of unnecessary stuff in the dict. In the above example it prints:

{'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}

How to resolve this issue? Thank you!

Upvotes: 2

Views: 974

Answers (2)

Daniel Butler
Daniel Butler

Reputation: 3756

If you can change the formula in the dict. Have it access the values in the dict. The problem is you haven’t defined x or y

dict_ = {'x': 1, 'y': 2, 'z': "dict_['x']+dict_['x']"}
dict_['z'] = eval(dict_['z'])

Upvotes: 2

Andrej Kesely
Andrej Kesely

Reputation: 195518

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:

{'x': 1, 'y': 2, 'z': 3}

Upvotes: 6

Related Questions