Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get average value from list of dictionary

I have lists of dictionary. Let's say it

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

I need get maximum, minimum, average value from it. I can get max and min values with below code:

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

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

like image 788
Gereltod Avatar asked Mar 13 '15 08:03

Gereltod


1 Answers

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

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

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

print float(sum(d['value'] for d in total)) / len(total)
like image 145
catavaran Avatar answered Oct 04 '22 04:10

catavaran