Search code examples
pythondictionaryeval

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!


Solution

  • 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}