Invert Dict

Invert Dict

Write a function that swaps the keys and values of a dictionary.

invert_dict(d)

Return a new dict where each original value becomes a key, and each original key becomes its value. You may assume all of d's values are unique (so no information is lost).

Examples

invert_dict({"a": "1", "b": "2", "c": "3"})   // → {"1": "a", "2": "b", "3": "c"}
invert_dict({"x": "hello", "y": "world"})     // → {"hello": "x", "world": "y"}

Walkthrough

Thinking it through

def invert_dict(d):
    return {value: key for key, value in d.items()}

d.items() gives you (key, value) pairs for every entry. The dict comprehension {value: key for key, value in d.items()} walks through those pairs and, for each one, builds a new entry with the roles reversed — value becomes the new key, key becomes the new value.

This is the dict-comprehension equivalent of the loop version:

def invert_dict(d):
    result = {}
    for key, value in d.items():
        result[value] = key
    return result

Both do exactly the same thing — the comprehension is just the more compact way to write "build a new dict from this loop" once you're comfortable with the syntax.

Why uniqueness matters

If two different keys mapped to the same value, inverting would try to create two entries with the same new key — and since a dict can only hold one value per key, the second one processed would silently overwrite the first. That's why the problem assumes unique values: without that guarantee, inverting would lose information.

main.py
Console
Press Run to execute your code, or Submit to test and complete this problem.