LearnFrenzy
Sign in Take a free test

Dictionaries · Dictionaries Coding Problems · Question 2

Invert a dictionary, grouping keys with the same value in Python Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 2 Back to Exercise

Invert a dictionary of student → grade into grade → list of students, keeping the students in their original order.

Solution
main.py Run
grades = {"Asha": "A", "Ravi": "B", "Meera": "A", "Dev": "C", "Kiran": "B"}

by_grade = {}
for student, grade in grades.items():
    by_grade.setdefault(grade, []).append(student)

for grade in sorted(by_grade):
    print(grade, by_grade[grade])

Output Verified by running it on Python 3

A ['Asha', 'Meera']
B ['Ravi', 'Kiran']
C ['Dev']

A plain swap {v: k …} would lose students who share a grade; setdefault builds a list per grade instead.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links