Exercice 119
We cosider the following dictionary of length N containing the students names as keys and their score lists as key values:
d = {'student1': listNote1, 'students2': listNotes2, ..., 'studentN': listNoteN}
Write a Python program that transforms this dictionary by replacing the score lists with their averages. Example if
d = {'student1': [14, 16, 18], 'students2': [12, 15, 17], 'student3': [16, 16, 13]}
, the program returns:
d = {'student1': 16.0, 'students2': 14.666666666666666, 'student3': 15.0}
Solution
# creation of a function which calculates the average of the elements for a given list def meanList (L): mean = 0 n = len (L) for x in L: mean = x + mean mean = mean/n return mean d = {'student1': [14, 16, 18], 'students2': [12, 15, 17], 'student3': [16, 16, 13]} # replacing lists by the means of their elements in the dictionary d for key in d: d [key] = meanList(d [key]) # display dictionary print ("The new dictionary is d =", d) # The output is: The new dictionary is d = {'student1': 16.0, 'students2': 14.666666666666666, 'student3': 15.0}
my-courses.net