Get average from dictionary list

I have a list of dictionaries. Let's say

total = [{"date": "2014-03-01", "value": 200}, {"date": "2014-03-02", "value": 100}{"date": "2014-03-03", "value": 400}] 

I need to get the maximum, minimum, average value from it. I can get the max and min values ​​using the code below:

 print min(d['value'] for d in total) print max(d['value'] for d in total) 

But now I need to get the average value from him. How to do it?

+5
source share
2 answers

Just divide the sum of the values ​​by the length of the list:

 print sum(d['value'] for d in total) / len(total) 

Note that integer division returns an integer value. This means that the average value of [5, 5, 0, 0] will be 2 instead of 2.5 . If you need a more accurate result, you can use the float() value:

 print float(sum(d['value'] for d in total)) / len(total) 
+13
source
 reduce(lambda x, y: x + y, [d['value'] for d in total]) / len(total) 

catavaran anwser is simpler you don't need lambda

+2
source

Source: https://habr.com/ru/post/1215283/


All Articles