Reputation: 37
I am trying to write a function called, averageGrades, that takes in a dictionary with keys representing students and values representing their grades. The function should return a new dictionary with keys representing students and values representing an average of their grades. The average should be an int and should be truncated
I have managed to write a bit of code, that gives me one average value, but it doesn't iterate through the list...
def averageGrades(diction):
avgDict = {}
for k, v in diction.items():
# v is the list of grades for student k
avgDict[k] = sum(v)/ float(len(v))
return avgDict
averageGrades({"Shana": [100, 90, 80], "Jody": [100, 70, 80, 90, 100], "Mike": [100, 100, 20]})
When i do this ^ I get {'Shana': 90.0} when i want {'Jody': 88, 'Mike': 73, 'Shana': 90}
Upvotes: 0
Views: 4495
Reputation: 20500
You should return your averageDict outside your for loop. If it is inside the for loop, return statement will return after the first iteration, which you don't want. Try as follows.
def averageGrades(diction):
avgDict = {}
for k, v in diction.items():
# v is the list of grades for student k
avgDict[k] = sum(v)/ float(len(v))
return avgDict
print(averageGrades({"Shana": [100, 90, 80], "Jody": [100, 70, 80, 90, 100], "Mike": [100, 100, 20]}))
Upvotes: 0
Reputation: 5733
Your return statement position is misplaced. In your case the return statement is inside the for loop, so return statement is returning dict with the first element, rather than the whole dict. Try the following code
def averageGrades(diction):
avgDict = {}
for k, v in diction.items():
# v is the list of grades for student k
avgDict[k] = sum(v)/ float(len(v))
return avgDict
Upvotes: 3
Reputation: 6132
This should do:
def averageGrades(diction):
avgDict = {}
for k, v in diction.items():
# v is the list of grades for student k
avgDict[k] = sum(v)/ float(len(v))
return avgDict
^^^^^
Indentation is important.
Your function stopped at the first loop because the return
statement was written before the for
statement ended
Upvotes: 1