Python - Cumulative Mean of Dictionary keys

When working with a list of dictionaries, you may need to calculate the cumulative mean of values for each key that appears across all dictionaries. This involves collecting all values for each unique key and computing their average.

Example

Below is a demonstration of calculating cumulative mean across multiple dictionaries ?

from statistics import mean

my_list = [{'hi': 24, 'there': 81, 'how': 11},
           {'hi': 16, 'how': 78, 'doing': 63}]

print("The list is:")
print(my_list)

my_result = dict()
for sub in my_list:
    for key, val in sub.items():
        if key in my_result:
            my_result[key].append(val)
        else:
            my_result[key] = [val]

for key, my_val in my_result.items():
    my_result[key] = mean(my_val)

print("The result is:")
print(my_result)
The list is:
[{'hi': 24, 'there': 81, 'how': 11}, {'hi': 16, 'how': 78, 'doing': 63}]
The result is:
{'hi': 20.0, 'there': 81.0, 'how': 44.5, 'doing': 63.0}

How It Works

The algorithm follows these steps:

  • Import statistics module ? The mean() function calculates the average of a list of numbers.

  • Initialize empty dictionary ? my_result will store lists of values for each key.

  • Collect values by key ? For each dictionary in the list, iterate through key-value pairs and group values by their keys.

  • Calculate means ? Replace each list of values with its mean using the mean() function.

Alternative Approach Using defaultdict

You can simplify the code using defaultdict ?

from statistics import mean
from collections import defaultdict

my_list = [{'hi': 24, 'there': 81, 'how': 11},
           {'hi': 16, 'how': 78, 'doing': 63}]

my_result = defaultdict(list)
for sub in my_list:
    for key, val in sub.items():
        my_result[key].append(val)

# Calculate means
final_result = {key: mean(values) for key, values in my_result.items()}
print("The result is:")
print(final_result)
The result is:
{'hi': 20.0, 'there': 81.0, 'how': 44.5, 'doing': 63.0}

Conclusion

Computing cumulative mean of dictionary keys involves collecting values for each key across multiple dictionaries and calculating their average. The statistics.mean() function simplifies the calculation, while defaultdict can make the code more concise.

Updated on: 2026-03-26T02:54:10+05:30

372 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements