Home > Back-end >  What is a nice way to get average of values in a list of nested dictionaries based on the keys?
What is a nice way to get average of values in a list of nested dictionaries based on the keys?

Time:03-04

What is a nice way to get average of values in a list of nested dictionaries based on the keys?

e.g.

[{'level1_1':{'level2_1': 1, 'level2_2': 2}, 'level1_2':{'level2_3': 3, 'level2_4': 4}}, 
{'level1_1':{'level2_1': 10, 'level2_2': 20}, 'level1_2':{'level2_3': 30, 'level2_4': 40}}]  

expected answer

{'level1_1':{'level2_1': 5.5, 'level2_2': 11}, 'level1_2':{'level2_3': 16.5, 'level2_4': 22}}

CodePudding user response:

You can use two dictionary comprehensions (one for each layer of dictionary) and a generator comprehension (to sum over all the elements in the list for each inner key). Note that this approach assumes that the schema for each element is identical:

data = [{'level1_1':{'level2_1': 1, 'level2_2': 2}, 'level1_2':{'level2_3': 3, 'level2_4': 4}}, 
{'level1_1':{'level2_1': 10, 'level2_2': 20}, 'level1_2':{'level2_3': 30, 'level2_4': 40}}]

result = {
    key: {
        inner_key: sum(entry[key][inner_key] for entry in data) / len(data) 
        for inner_key in value
    }
    for key, value in data[0].items()
}
print(result)

Output:

{'level1_1': {'level2_1': 5.5, 'level2_2': 11.0}, 'level1_2': {'level2_3': 16.5, 'level2_4': 22.0}}
  • Related