I try to select keys and values in a json file and calculate average values. If a key is equal to a certain value, I want to take them and to calculate the average value.

for total in data_total: object_id = total["objectID"] model = total["modele"] marque = total["marque"] cote_2020 = total["cote"]["cote_2020"]["cote_2020_eu"]["cote_2020_base_eu"] #models list if model == "Ace": model_ace = [] model_cote_ace = cote_2020 model_ace.append(model_cote_ace) mean_ace = statistics.mean(model_ace) mean_ace = round(mean_ace) cote_2020_ace = mean_ace

An sample of the json file:

{ "objectID": 10028, "modele": "Ace", "cote_actual": { "cote_actual_eu": { "cote_actual_base_eu": 342327 }, }, }, { "objectID": 10029, "modele": "Ace", "cote_actual": { "cote_actual_eu": { "cote_actual_base_eu": 20000 }, },

But I have thousands of different models. Have I to create thousands of `if model == something`

conditions and calculate average values based on models ?

## Answer

If *most* of the calculations are the same, and you are customizing the calculation for only a handful of the models, a dictionary with functions you can call makes sense:

def default(entry): # Pass in total, or whatever object makes sense and perform calculations. result = 0 # actually figure out the result here return result def ace(entry): # Ace instances need special handling result = 12 # customize this calculation somehow return result funcs = {'Ace': ace} for total in data_total: modele = total['modele'] mean = funcs.get(modele, default)(total)