Python problem 20 of 30

Invert a dictionary

  • Python
  • Medium

Write invert(d) that swaps keys and values. Several keys can share a value, so each new value should be a list of the original keys, in their original order.

invert({"ada": "CS", "linus": "CS", "grace": "Math"})
# {"CS": ["ada", "linus"], "Math": ["grace"]}
Show hint

d.setdefault(key, []) returns the list stored under key, creating an empty one first if needed.

Show solution
def invert(d):
    out = {}
    for key, value in d.items():
        out.setdefault(value, []).append(key)
    return out

A plain swap like {v: k for k, v in d.items()} silently loses keys that share a value, because later ones overwrite earlier ones. Grouping into lists keeps them all. collections.defaultdict(list) is another clean way to write it. The values must be hashable to become keys.

Want a problem like this every day? See today's problem and keep a streak going.