Evaluating math expression on dictionary variables

2019-08-18 23:47发布

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 according to regular expressions and print out multiple fields from an event.

Now I'd like to be able to evaluate simple mathematical operations when printing fields. This way I could just say something like

    ./print.py type download/upload

and it would print the type and the upload to download ratio. My problem is that I can't use eval() because the values are actually inside a dict.

Is there a simple solution?

2条回答
甜甜的少女心
2楼-- · 2019-08-19 00:18

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.

查看更多
成全新的幸福
3楼-- · 2019-08-19 00:29

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
查看更多
登录 后发表回答