-1

I am facing difficulty in writing a method that updates the dictionaries based on certain dynamic action

I have a list of dictionaries like

data_list = [{'x_data':1.987, 'y_data':25.9, 'plant_id':12}, {'x_data':1.024, 'y_data':19.9, 'plant_id':14}]

action = "x_data+y_data"
#or it may be "y_data/x_data" or "x_data*y_data" and "1/(x_data*y_data").

output : [{z_data:27.887 'plant_id':12}, {z_data:20.925, 'plant_id':14}]

So, I want a method that takes list and action and gives an updated list.

update_dictionaries(data_list, action):
    return updated_list

Thank you.

2 Answers2

2

Use pythons eval function https://docs.python.org/3/library/functions.html#eval

You should be able to use the following example to modify your code to do what you want

def my_func(x,y,action):
    try:
        z = eval(action)
    except:
        z = None
    return z


my_func(1,2,"x+y")
#3

my_func(2,3,"x*y")
#6

Hope this helps.

tomgalpin
  • 1,943
  • 1
  • 4
  • 12
1
def update_dictionaries(data_list, action):
action = action.replace("x_data","dic['x_data']")
action = action.replace("y_data","dic['y_data']")
for dic in data_list:
    ans = eval(action)
    dic['z_data']=ans
    dic.pop('x_data',None)
    dic.pop('y_data',None)
return data_list

Thank me later!

vBrail
  • 181
  • 10