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.
values = [ {'index': 0, 'weight': 0.5}, {'index': 1, 'weight': 0.5}, {'index': 0, 'weight': 0.5}, {'index': 1, 'weight': 0.5}, {'index': 0, 'weight': 0.0}, {'index': 1, 'weight': 1.0}, {'index': 0, 'weight': 0.0}, {'index': 1, 'weight': 1.0}, {'index': 0, 'weight': 0.0}, {'index': 1, 'weight': 1.0}, {'index': 0, 'weight': 1.0}, {'index': 1, 'weight': 0.0}, {'index': 0, 'weight': 1.0}, {'index': 1, 'weight': 0.0}, {'index': 0, 'weight': 1.0}, {'index': 1, 'weight': 0.0} ]
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:
print(sum(v['weight'] for v in values ) / len(values))
Advertisement
Answer
You need to group weights by index. defaultdict from the built-in collections module is useful here.
from collections import defaultdict total = defaultdict(int) cnts = defaultdict(int) for d in values: # add weights total[d['index']] += d['weight'] # count indexes cnts[d['index']] += 1 # find the mean [{'index': k, 'mean weight': total[k]/cnts[k]} for k in total] # [{'index': 0, 'mean weight': 0.5}, {'index': 1, 'mean weight': 0.5}]