Invert a Dictionary
Write invert_dict(d) that returns a dictionary whose keys are the values of d and whose values are lists of the keys that had that value, in the order they appear in d.
{"a": 1, "b": 2, "c": 1} becomes {1: ["a", "c"], 2: ["b"]}.
Understand the problem
Find what goes wrong with a plain swap.
What does {v: k for k, v in {"a": 1, "b": 2, "c": 1}.items()} give?
{1: "a", 2: "b"}{1: "c", 2: "b"}{1: ["a", "c"], 2: ["b"]}
Both a and c map to 1. The comprehension writes 1: "a" first and then overwrites it with 1: "c". The key a is lost silently. Collisions need a list.
Which dictionary method returns the existing list for a key, or creates and stores an empty list first?
d.get(key)d.setdefault(key, [])d.update(key)
d.setdefault(key, []) returns d[key] if the key exists; otherwise it stores [] under the key and returns it. So d.setdefault(k, []).append(x) groups items in one line.
Write the solution
Return the inverted dictionary.
def invert_dict(d):
# Write your code here.
pass
Hint 1: a question to ask yourself
What must each value of the new dictionary be, so that no key is ever lost?
Hint 2: the shape of the answer
Loop over d.items(). For each (key, value), put the key into the list stored under value.
Reflect
Solution
def invert_dict(d):
inverted = {}
for key, value in d.items():
inverted.setdefault(value, []).append(key)
return inverted
Another way: defaultdict
from collections import defaultdict
def invert_dict(d):
inverted = defaultdict(list)
for key, value in d.items():
inverted[value].append(key)
return dict(inverted)
What this tests: iterating over items(), setdefault or defaultdict(list), and noticing silent data loss.
The idea: the new dictionary maps each old value to all the old keys that had it. Grouping like this is one of the most reused dictionary patterns.
Values must be hashable to become keys. If a value were a list, inverted.setdefault(value, ...) would raise a TypeError.
Cost: O(n).
What an interviewer might ask next: When you know the values are all different, the one-line comprehension is enough. How would you check that first? (len(set(d.values())) == len(d).)
VISIBLE = 3
CASES = [
(({'a': 1, 'b': 2, 'c': 1},), {1: ['a', 'c'], 2: ['b']}, 'two keys share a value'),
(({},), {}, 'an empty dictionary'),
(({'x': 'red', 'y': 'blue'},), {'red': ['x'], 'blue': ['y']}, 'all values different'),
(({'a': 0, 'b': 0, 'c': 0},), {0: ['a', 'b', 'c']}, 'all values equal'),
(({'one': 1, 'uno': 1, 'ein': 1, 'two': 2},), {1: ['one', 'uno', 'ein'], 2: ['two']}, 'the order of the keys is kept'),
(({1: 'a', 2: 'a'},), {'a': [1, 2]}, 'number keys'),
]