Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 671
tikka Avatar asked Jun 03 '26 09:06

tikka


1 Answers

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}
like image 108
Andrej Kesely Avatar answered Jun 04 '26 23:06

Andrej Kesely



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!