Invert a dictionary with duplicates

EasyCollections Programs · 19 of 20

Write a Python program to invert a grade dictionary into grade -> students.

Advertisement
Output
{'A': ['asha', 'meena'], 'B': ['ravi'], 'C': ['john']}

Approach

  1. defaultdict(list).

Solution

Python
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']}
Advertisement

Learn the concept

New to this topic? Read the lesson, then come back.

More collections programs

← All 20 Collections Programs