1

Let's say I have this operation as a string variable:

formula = '{a} + {b}'

And I have a dictionary such as

data = {'a': 3, 'b': 4}

Is there such a functionality in some library where:

evaluate(operation = formula, variables = data)

gives:

7
Delosari
  • 677
  • 2
  • 17
  • 29

3 Answers3

4

If you are using Python3 you can do something like this with string formatting:

>>> import ast
>>> data = {'a': 3, 'b': 4}
>>> formula = '{a} + {b}'
>>> res_string = formula.format(a=data['a'], b=data['b'])
>>> res = ast.literal_eval(res_string)
>>> print(res)
7

Or even better as pointed by Steven in the comments:

res_string = formula.format(**data)

Or if you are using Python3.6 you can even do this with the cool f-string:

>>> f"{sum(data.values())}"
'7'
Mohammad Yusuf
  • 16,554
  • 10
  • 50
  • 78
1

Although not recomended, you can use eval(). Check out:

>>> data = {'a': 3, 'b': 4}
>>> eval('{a} + {b}'.format(**data))
>>> 7

eval() will try to execute the given string as python code. For more information about python format you can take a look at the really nice pyformat site.

Carlos Afonso
  • 1,927
  • 1
  • 12
  • 22
  • Thank you very much for this insight. It also helped me find numexpr. I need to play a bit more with them – Delosari Feb 09 '17 at 12:11
1

First you need to parse your string, then you need to have a proper dictionary in order to map the founded operators to their equivalent functions, which you can use operator module for this aim:

In [54]: from operator import add

In [55]: operators = {'+': add}  # this is an example, if you are dealing with more operations you need to add them to this dictionary

In [56]: def evaluate(formula, data):
             a, op, b = re.match(r'{(\w)} (\W) {(\w)}', formula).groups()
             op = operators[op]
             a, b = data[a], data[b]
             return op(a, b)
   ....: 

In [57]: evaluate(formula, data)
Out[57]: 7
Mazdak
  • 105,000
  • 18
  • 159
  • 188
  • Thank you for the reply... this should be more efficient when you one only need to solve one type of equation :) – Delosari Feb 09 '17 at 14:19