Evaluating math expression on dictionary variables

安稳与你 提交于 2019-12-25 01:55:36

问题


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?


回答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.




回答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


来源:https://stackoverflow.com/questions/7515397/evaluating-math-expression-on-dictionary-variables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!