robert williams robert williams - 9 months ago 47
Python Question

assigning a value from dictionary to equation

i want to assign a value to a string equation but i am stuck with the logic.

dic1 = {'d': '2', 'a': '1', 'c': '3', 'b': '2'}
equation_string = 'ab+cd'

i want to the output like:

'12+32' = 44

My Logic:

1 -> writing a for loop to assign the values to the string but i don't know how to skip '+' sign in the string.

for itr in range(0,len(equation_string)):
equation_String[itr] = dict1[equation_str[itr]]

Answer Source

In order to achieve it. You need to firstly replace the key in equation_string of dic1 with the corresponding value using string.replace(). When you made all the replacements within the string, execute the string expression using eval(). Below is the sample code:

>>> dic1 = {'d': '2', 'a': '1', 'c': '3', 'b': '2'}
>>> equation_string = 'ab+cd'
>>> for k, v in dic1.iteritems():
...     equation_string = equation_string.replace(k, v)
>>> equation_string
'12+32'   # Updated value of equation_string
>>> eval(equation_string)