Skip to content
Advertisement

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.

JavaScript

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

Advertisement

Answer

You need to group weights by index. defaultdict from the built-in collections module is useful here.

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement