Search code examples
pythondictionaryaverage

Get the average of dictionary values?


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


Solution

  • This answer was intended for Python2, which is now dead

    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))
    

    In Python3, the iteritems() method is no longer necessary, can use items() directly.

    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.