pythonlistdictionaryaverage

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?


Solution

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