Editor

Invert a Dictionary

#249 · Python idioms · Beginner · 40 XP · about 7 min

A dictionary d maps people to their favourite colour. Write invert(d) that turns it inside out: the result maps each colour (each value of d) to a list of the people (the keys of d) who chose it.

  • Each list of keys is in alphabetical order.
  • The values appear in the new dictionary in the order they first turn up in d.

Examples

invert({'ana': 'red', 'ben': 'blue', 'cy': 'red'})
# returns {'red': ['ana', 'cy'], 'blue': ['ben']}
invert({'zoe': 1, 'adam': 1, 'max': 2})
# returns {1: ['adam', 'zoe'], 2: ['max']}
invert({})  # returns {}

Note

The keys of d are strings, and its values can be strings or numbers.

Fastest solvers

Leaderboard

First solves only, ranked by stars and then time.