Home > Software engineering >  average of dictionary values
average of dictionary values

Time:11-05

I need to create a function that takes dictionary as an argument. the function returns the average result for all rounds. here's an example of how the code should work:

>>> find_average({'round 1': [1, 2, 3, 4], 'round 2': [3, 4, 2, 7], 'round 3': [2, 7, 5, 6]})
3.8

I tried this:

def find_average(dictionary):
    average = sum(dictionary.values())/len(dictionary)
    return average

but received an error:

TypeError: unsupported operand type(s) for  : 'int' and 'list'

What should I do?

CodePudding user response:

You need to find the average of each value in the dictionary and find the average of that list.

def find_average(dictionary):
    sums = [sum(lst)/len(lst) for lst in dictionary.values()]
    return sum(sums)/len(sums)

The result will be 3.8333333333333335 but you can round the result like this round(sum(sums)/len(sums), 1) which gives you 3.8

CodePudding user response:

you cant use sum for an dictionary

CodePudding user response:

use itertools.chain

from itertools import chain
d = {'round 1': [1, 2, 3, 4], 'round 2': [3, 4, 2, 7], 'round 3': [2, 7, 5, 6]}
sum(chain(*d.values()))/len(list(chain(*d.values())))

#output : 3.8333333333333335

CodePudding user response:

you were summing the dictionary values which were each one is a list, and dividing by the length of keys which is incorrect

print(sum(dicti.values()))
""" 
Traceback (most recent call last):
  File "/tmp/main.py", line 2, in <module>
    import user_code
  File "/tmp/user_code.py", line 11, in <module>
    print(find_average({'round 1': [1, 2, 3, 4], 'round 2': [3, 4, 2, 7], 'round 3': [2, 7, 5, 6]}))
  File "/tmp/user_code.py", line 6, in find_average
    print(sum(dicti.values()))
TypeError: unsupported operand type(s) for  : 'int' and 'list'

""" 

the reason previous code fails is because sum operates on lists NOT list of lists the following run returns the correct answer

def find_average(dicti):
    s = 0
    c = 0
    for i in dicti.values():
        s  = sum(list(i))
        c  = len(list(i))
    return s/c;
find_average({'round 1': [1, 2, 3, 4], 'round 2': [3, 4, 2, 7], 'round 3': [2, 7, 5, 6]})) #  3.8333333333333335
  • Related