I have a list of dictionaries that have an “index” and a “weight” value. I want to average the dictionaries based on any unique index. So, with the below example, how can I find the average weight for any given index (e.g. 0, 1, 250, etc.)? There will be 8 total elements for each index.
JavaScript
x
19
19
1
values = [
2
{'index': 0, 'weight': 0.5},
3
{'index': 1, 'weight': 0.5},
4
{'index': 0, 'weight': 0.5},
5
{'index': 1, 'weight': 0.5},
6
{'index': 0, 'weight': 0.0},
7
{'index': 1, 'weight': 1.0},
8
{'index': 0, 'weight': 0.0},
9
{'index': 1, 'weight': 1.0},
10
{'index': 0, 'weight': 0.0},
11
{'index': 1, 'weight': 1.0},
12
{'index': 0, 'weight': 1.0},
13
{'index': 1, 'weight': 0.0},
14
{'index': 0, 'weight': 1.0},
15
{'index': 1, 'weight': 0.0},
16
{'index': 0, 'weight': 1.0},
17
{'index': 1, 'weight': 0.0}
18
]
19
I know I can get the average weight for the whole list using the following code, but I’m not sure how to do this per unique index:
JavaScript
1
2
1
print(sum(v['weight'] for v in values ) / len(values))
2
Advertisement
Answer
You need to group weights by index. defaultdict from the built-in collections module is useful here.
JavaScript
1
12
12
1
from collections import defaultdict
2
total = defaultdict(int)
3
cnts = defaultdict(int)
4
for d in values:
5
# add weights
6
total[d['index']] += d['weight']
7
# count indexes
8
cnts[d['index']] += 1
9
# find the mean
10
[{'index': k, 'mean weight': total[k]/cnts[k]} for k in total]
11
# [{'index': 0, 'mean weight': 0.5}, {'index': 1, 'mean weight': 0.5}]
12