Invert a dictionary with repeated values

EasyDictionary Programs · 90 of 94

Write a Python program to invert a dictionary whose values repeat, collecting keys in lists.

Advertisement
Input
{"alex": 1, "bob": 2, "martin": 1, "robert": 2}
Output
{1: ['alex', 'martin'], 2: ['bob', 'robert']}

Approach

  1. setdefault(v, []).append(k).

Solution

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

Learn the concept

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

More dictionary programs

← All 94 Dictionary Programs