Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Finding average value in list of dictionaries based on another unique value

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))

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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}]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading