Python Practice › Collections Programs › Program 19
Invert a dictionary with duplicates
Write a Python program to invert a grade dictionary into grade -> students.
Output
{'A': ['asha', 'meena'], 'B': ['ravi'], 'C': ['john']}Approach
defaultdict(list).
Solution
from collections import defaultdict grades = {"asha": "A", "ravi": "B", "meena": "A", "john": "C"}by_grade = defaultdict(list)for student, grade in grades.items(): by_grade[grade].append(student)print(dict(sorted(by_grade.items())))Output
{'A': ['asha', 'meena'], 'B': ['ravi'], 'C': ['john']}Learn the concept
New to this topic? Read the lesson, then come back.