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 1
A dict comprehension{v: k for k, v in d.items()} keeps only the last key for each value.Hint 2
out.setdefault(v, []).append(k) creates the list the first time a value is seen.Hint 3
Sort each list at the end.Learn the concepts
- Dict, set and list methods · 7 min read. get, setdefault, views, set operations, append versus extend, remove and slicing, with the traps in each.
- Lists, dicts and sets: what each operation costs · 7 min read. Pick the container from the question, and why a set turns an hour-long loop into a second.
More Python problems
- Flatten a Nested List · Easy
- Squares of the Even Numbers · Easy
- Top K Frequent Words · Easy
- Merge Dicts and Sum Shared Keys · Easy
- Group Records by Key · Easy
- Count Words in Reviews · Easy
- Zip Columns into Records · Easy
- Find the Missing IDs · Easy
- Safe Min and Max · Easy
- Sort by Several Keys · Medium
- Fix the Mutable Default Argument · Medium
- Override a Config Without Changing It · Medium
- Keep the Last N Events · Medium