Python Practice › Dictionary Programs › Program 90
Invert a dictionary with repeated values
Write a Python program to invert a dictionary whose values repeat, collecting keys in lists.
Input
{"alex": 1, "bob": 2, "martin": 1, "robert": 2}Output
{1: ['alex', 'martin'], 2: ['bob', 'robert']}Approach
setdefault(v, []).append(k).
Solution
d = {"alex": 1, "bob": 2, "martin": 1, "robert": 2}inverted = {}for k, v in d.items(): inverted.setdefault(v, []).append(k)print(inverted)Output
{1: ['alex', 'martin'], 2: ['bob', 'robert']}Learn the concept
New to this topic? Read the lesson, then come back.