Editor

Invert a Dictionary

Beginner · Write the code · from 50 Python Practice Problems with Instant Answer Checking (Beginner to Advanced)

From the lesson: 50 Python Practice Problems with Instant Answer Checking (Beginner to Advanced)

Fifty problems, each with a code editor and real tests. Write your solution, press Check, and see exactly which cases pass. Stuck? Hints reveal one at a time, and the solution unlocks once you have checked at least once. Your code and progress are saved in this browser.

Read the lesson

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

invert({"ann": "red", "bob": "blue", "cy": "red"})
->  {"red": ["ann", "cy"], "blue": ["bob"]}
def invert(d):
pass
Solution unlocks after your first Check

What Check runs

Your code runs first, then each of these lines. The output must match exactly.

RunsExpected output
invert({"ann": "red", "bob": "blue", "cy": "red"}){'red': ['ann', 'cy'], 'blue': ['bob']}
invert({}){}

More practice problems

All Python exercises · 50 practice problems