Home > other >  Mean values over nested dictionary of dictionary
Mean values over nested dictionary of dictionary

Time:10-06

I have the following nested dictionary in Python:

     {'data1':{'IOU':{'B':0.1,'G':0.3},
              'lines':{'B':{'accuracy':0.3, "recall":0.3},'G':{'accuracy':0.1, "recall":0.6}}},
      'data2':{'IOU':{'B':0.2,'G':0.8},
              'lines':{'B':{'accuracy':0.5, "recall":0.3},'G':{'accuracy':0.9, "recall":0.5}}}}

And from this I want to create a new dictionary like this:

{'lines':{'B':{'accuracy':0.4, 'recall': 0.3}, 'G':{'accuracy':0.5, "recall":0.55}}}}

I basically want to get a nested dictionary for the 'lines' key such that:

  • the new keys are B and G
  • the new values are the mean values for each key (B and G) and each metric (accuracy and recall)

I am struggling with this, could anyone suggest how to code the?

CodePudding user response:

You could use dict comprehension on your input dictionary (let's call it d_in):

letters = ["B", "G"]
metrics = ["accuracy", "recall"]

result = {
    "lines": {
        letter: {
            metric: (
                sum(data["lines"][letter][metric] for data in d_in.values()) / len(d_in)
            )
            for metric in metrics
        }
        for letter in letters
    }
}
  • Related