Search⌘ K
AI Features

Solution: Create a Dictionary and Replace Key-value Pairs

Explore how to create a dictionary in Python with student names and scores, then replace their values by computing total and average scores. Understand how to iterate over nested dictionaries, update values efficiently, and identify the top student based on average scores.

We'll cover the following...

The solution to the problem of creating a dictionary that contains students’ names and scores, and then replacing the scores with the total and average scores is given below.

Solution

Python 3.8
students = {
'John' : { 'Math' : 48, 'English' : 60, 'Science' : 95},
'Richard' : { 'Math' : 75,'English' : 68,'Science' : 89},
'Charles' : { 'Math' : 45,'English' : 66,'Science' : 87}
}
top_student = ''
top_student_score = 0
for nam, info in students.items( ) :
total = 0
for sub, scores in info.items( ) :
total = total + scores
avg = int(total / 3)
students[nam] = {'Total' : total, 'Average' : avg}
if avg > top_student_score :
top_student = nam
top_student_score = avg
print(students)
print ("Top student of the class:" , top_student)
print("Top student's score:", top_student_score)

Explanation

  • Lines 1–5: We create a dictionary students that contains
...