Python 3.4 - How to get the average of dictionary values? [closed]

蹲街弑〆低调 提交于 2019-11-30 16:21:40

问题


I have the following dictionary:

StudentGrades = {
    'Ivan': [4.32, 3, 2],
    'Martin': [3.45, 5, 6],
    'Stoyan': [2, 5.67, 4],
    'Vladimir': [5.63, 4.67, 6]
}

I want to make a function that prints the average of the grades of the students, i.e. the average of the values, but I have no idea how. Can you help me please?


回答1:


Okay, so let's iterate over all dictionary keys and average the items:

avgDict = {}
for k,v in StudentGrades.iteritems():
    # v is the list of grades for student k
    avgDict[k] = sum(v)/ float(len(v))

now you can just see :

avgDict
Out[5]: 
{'Ivan': 3.106666666666667,
 'Martin': 4.816666666666666,
 'Stoyan': 3.89,
 'Vladimir': 5.433333333333334}

From your question I think you're queasy about iteration over dicts, so here is the same with output as a list :

avgList = []
for k,v in StudentGrades.iteritems():
    # v is the list of grades for student k
    avgDict.append(sum(v)/ float(len(v)))

Be careful though : the order of items in a dictionary is NOT guaranteed; this is, the order of key/values when printing or iterating on the dictionary is not guaranteed (as dicts are "unsorted"). Looping over the same identical dictionary object(with no additions/removals) twice is guaranteed to behave identically though.




回答2:


If you don't want to do the simple calculation use statistics.mean:

from statistics import mean

StudentGrades = {
    'Ivan': [4.32, 3, 2],
    'Martin': [3.45, 5, 6],
    'Stoyan': [2, 5.67, 4],
    'Vladimir': [5.63, 4.67, 6]
}

for st,vals in StudentGrades.items():
    print("Average for {} is {}".format(st,mean(vals)))



回答3:


from scipy import mean
map(lambda x: mean(StudentGrades[x]), StudentGrades)

Generates this output:

[3.1066666666666669,
 3.8900000000000001,
 5.4333333333333336,
 4.8166666666666664]

If you prefer a non-scipy solution one could use sum and len like supposed by Jiby:

map(lambda x: sum(StudentGrades[x])/len(StudentGrades[x]), StudentGrades)

EDIT: I am terribly sorry, I forgot you want a Python 3.4 solution, therefore (because you would get a map object returned) you need, for example, an additional list command:

from scipy import mean
list(map(lambda x: mean(StudentGrades[x]), StudentGrades))

This will return the desired output.



来源:https://stackoverflow.com/questions/30687244/python-3-4-how-to-get-the-average-of-dictionary-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!