Evaluating Math Expression On Dictionary Variables
I'm doing some work evaluating log data that has been saved as JSON objects to a file. To facilitate my work I have created 2 small python scripts that filter out logged entries ac
Solution 1:
eval
optionally takes a globals
and locals
dictionaries. You can therefore do this:
namespace = dict(foo=5, bar=6)
print eval('foo*bar', namespace)
Keep in mind that eval
is "evil" because it's not safe if the executed string cannot be trusted. It should be fine for your helper script though.
For completness, there's also ast.literal_eval()
which is safer but it evaluates literals only which means there's no way to give it a dict.
Solution 2:
You could pass the dict
to eval()
as the locals
. That will allow it to resolve download
and upload
as names if they are keys in the dict
.
>>> d = {'a': 1, 'b': 2}
>>> eval('a+b', globals(), d)
3
Post a Comment for "Evaluating Math Expression On Dictionary Variables"