Get average value from list of dictionary
28,837
Solution 1
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)
Solution 2
I needed a more general implementation of the same thing to work on the whole dictionary. So here is one simple option:
def dict_mean(dict_list):
mean_dict = {}
for key in dict_list[0].keys():
mean_dict[key] = sum(d[key] for d in dict_list) / len(dict_list)
return mean_dict
Testing:
dicts = [{"X": 5, "value": 200}, {"X": -2, "value": 100}, {"X": 3, "value": 400}]
dict_mean(dicts)
{'X': 2.0, 'value': 233.33333333333334}
Solution 3
reduce(lambda x, y: x + y, [d['value'] for d in total]) / len(total)
catavaran's anwser is more easy, you don't need a lambda
Author by
Gereltod
Updated on July 23, 2020Comments
-
Gereltod almost 4 years
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?
-
catavaran about 9 yearsI added the note about float results.
-
avans almost 2 yearsHuh, why looping several times over the same list? Wouldn't it be better to loop over the list elems and then sum up the dict elements in the inner on a reference to the i'th list element?