Skip to content

4. Invert a Dictionary

Difficulty: Easy · Topic: Core Python & data structures

Write invert(d): map each value of d to the list of keys that had it. Several keys can share a value, so every value maps to a list, sorted in ascending order.

Example: {'asha': 'eng', 'ben': 'sales', 'chitra': 'eng'} becomes {'eng': ['asha', 'chitra'], 'sales': ['ben']}.

Your code runs in CPython on our servers against 5 tests, including hidden ones.

Sample test

invert({'asha': 'eng', 'ben': 'sales', 'chitra': 'eng'})

Expected: {'eng': ['asha', 'chitra'], 'sales': ['ben']}

Hints

Hint 1A dict comprehension {v: k for k, v in d.items()} keeps only the last key for each value.
Hint 2out.setdefault(v, []).append(k) creates the list the first time a value is seen.
Hint 3Sort each list at the end.

Learn the concepts

More Python problems

All Python problems