Given a data-structure like this:
[{'a':1, 'b': 2}, {'c':3 }, {'a':4, 'c':9}, {'d':0}, {'d': 0, 'b':6}]
The goal is to parse the data to produce:
{'a': 2.5, 'b': 4, 'c': 6, 'd': 0}
by doing:
- Accumulate the values for each unique key,
- Average the values per key
What's a simple way to achieve the data munging as desired above?
I've tried the following and it works:
from collections import defaultdict
from statistics import mean
x = [{'a':1, 'b': 2}, {'c':3 }, {'a':4, 'c':9}, {'d':0}, {'d': 0, 'b':6}]
z = defaultdict(list)
for y in x:
for k, v in y.items():
z[k].append(v)
output = {k: mean(v) for k,v in z.items()}
But is there a simpler way to achieve the same data-parsing? Maybe with collections.Counter or something?