Use student names as dictionary keys and numeric grades as values. This complete example creates three entries, updates one grade and calculates the mean:
student_grades = {"Alice": 85, "Bob": 92, "Carol": 78}
student_grades["Bob"] = 95
for name, grade in student_grades.items():
print(f"{name}: {grade}")
average = sum(student_grades.values()) / len(student_grades)
print(f"Average: {average:.1f}")Expected output:
Alice: 85
Bob: 95
Carol: 78
Average: 86.0Handle missing names and empty data
print(student_grades.get("Dana", "No grade recorded"))
if student_grades:
average = sum(student_grades.values()) / len(student_grades)
else:
average = NoneIndexing a missing name with square brackets raises KeyError; get() lets you choose a fallback. Check for an empty dictionary before dividing by its length. Keep grades numeric if you plan to average them.
Choose keys that identify students
A dictionary has unique keys. Assigning a second grade to "Bob" replaces Bob’s previous value. If two students share a name, use a unique student ID as the key and keep the name and grades inside that student’s record.
For names containing punctuation, see apostrophes in strings. If you run the example and see no output, check how you are executing the Python file.
Sources and verification
The dictionary examples and their stated output are executed in the local Python verification run.
