user3412550
user3412550

Reputation: 21

how do I sum up this python Dictionary and get the average?

d =[{'C': 0, 'B': 2.0, 'A': 7.0, 'D': 3.0}, {'C': 2.0, 'B': 0, 'A': 5.0, 'D': 5.0}, {'C': 7.0, 'B': 5.0, 'A': 0, 'D': 10.0}, {'C': 3.0, 'B': 5.0, 'A': 10.0, 'D': 0}]

how do I sum up this python Dictionary and get the average ?...

Upvotes: 0

Views: 82

Answers (3)

shantanoo
shantanoo

Reputation: 3704

>>> from functools import reduce
>>> d
[{'D': 3.0, 'A': 7.0, 'C': 0, 'B': 2.0}, {'D': 5.0, 'A': 5.0, 'C': 2.0, 'B': 0}, {'D': 10.0, 'A': 0, 'C': 7.0, 'B': 5.0}, {'D': 0, 'A': 10.0, 'C': 3.0, 'B': 5.0}]
>>> l = len(d)
>>> s = reduce(lambda x,y: {z:x[z]+y[z] for z in ['A','B','C','D']}, d)
>>> s = {x:s[x]/l for x in s}
>>> s
{'D': 4.5, 'A': 5.5, 'C': 3.0, 'B': 3.0}
>>>

Upvotes: 1

SZIEBERTH Ádám
SZIEBERTH Ádám

Reputation: 4196

You dont explicitly stated how you want to average the values.

You can get all the values with this genexp:

>>> [v for subdict in d for v in subdict.values()]
[2.0, 0, 7.0, 3.0, 0, 2.0, 5.0, 5.0, 5.0, 7.0, 0, 10.0, 5.0, 3.0, 10.0, 0]

To average the sums of dictionaries by number of dictionaries:

>>> sum(v for subdict in d for v in subdict.values())/len(d)
16.0

To average them by subdictionary:

>>> [sum(subdict.values())/len(subdict) for subdict in d]
[3.0, 3.0, 5.5, 4.5]

If you just want the average 'A':

>>> sum(v for subdict in d for k, v in subdict.items() if k == 'A')/len(d)
5.5

Upvotes: 0

user3352495
user3352495

Reputation: 391

Here is how to get the averages of the 'C' field. Just change the 'C' to the desired fields for the other averages.

cAVG = sum(map(lambda item: item['C'], d))/len(d);

Upvotes: 0

Related Questions