Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Find average in dict elements

I have dict like:

dict = [{'a':2, 'b':3}, {'b':4}, {'a':1, 'c':5}]

I need to get average of all different keys. Result should looks like:

avg = [{'a':1.5, 'b':3.5, 'c':5}]

I can get summary of all keys, but Im failing to realize how can I count same keys in order to get average number.

like image 978
RhymeGuy Avatar asked Jul 13 '26 07:07

RhymeGuy


1 Answers

You could create an intermediate dictionary that collects all encountered values as lists:

dct = [{'a':2, 'b':3}, {'b':4}, {'a':1, 'c':5}]
from collections import defaultdict
intermediate = defaultdict(list)

for subdict in dct:
    for key, value in subdict.items():
        intermediate[key].append(value)

# intermediate is now: defaultdict(list, {'a': [2, 1], 'b': [3, 4], 'c': [5]})

And finally calculate the average by dividing the sum of each list by the length of each list:

for key, value in intermediate.items():
    print(key, sum(value)/len(value))

which prints:

b 3.5
c 5.0
a 1.5
like image 198
MSeifert Avatar answered Jul 15 '26 22:07

MSeifert



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!