Medium: Interview Core · Problem 35 of 82

Invert a Dictionary

MediumDictionaries and SetsPython

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. {1: "a", 2: "b"}
  2. {1: "c", 2: "b"}
  3. {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?

  1. d.get(key)
  2. d.setdefault(key, [])
  3. 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).)