Programs & Examples
Dictionaries · Study material
Student report from a nested dict
Each student maps to a dict of subject marks: averages, each student's best subject and each subject's topper fall out of values(), max() with key= and a dict comprehension.
marks = {
"Asha": {"math": 95, "physics": 88, "chemistry": 91},
"Ravi": {"math": 72, "physics": 65, "chemistry": 80},
"Meera": {"math": 85, "physics": 92, "chemistry": 79},
}
for name, subjects in marks.items():
avg = sum(subjects.values()) / len(subjects)
best = max(subjects, key=subjects.get)
print(f"{name:<6} average {avg:5.1f} best: {best}")
subjects = marks["Asha"].keys()
toppers = {s: max(marks, key=lambda n: marks[n][s]) for s in subjects}
print(toppers)
Asha average 91.3 best: math
Ravi average 72.3 best: chemistry
Meera average 85.3 best: physics
{'math': 'Asha', 'physics': 'Meera', 'chemistry': 'Asha'}Word counting and grouping
The counting example on the Introduction tab builds the same word counts with get(), setdefault(), defaultdict and Counter.