17

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?

Hedde van der Heide
  • 21,841
  • 13
  • 71
  • 100
Gereltod
  • 2,043
  • 8
  • 25
  • 39

4 Answers4

32

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)
catavaran
  • 44,703
  • 8
  • 98
  • 85
7

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}
dsalaj
  • 2,857
  • 4
  • 34
  • 43
  • Huh, 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? – Wör Du Schnaffzig May 25 '22 at 09:52
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

Hedde van der Heide
  • 21,841
  • 13
  • 71
  • 100
1

An improvement on dsalaj's answer if the values are numeric lists instead:

def dict_mean(dict_list):
    mean_dict = {}
    for key in dict_list[0].keys():
        mean_dict[key] = np.mean([d[key] for d in dict_list], axis=0)
    return mean_dict
Joe
  • 418
  • 4
  • 12