You have a dict mapping user IDs to usernames — {1: "alex", 2: "blair", 3: "casey"} — and you want the opposite lookup: username to ID. {"alex": 1, "blair": 2, "casey": 3}. How do you invert a dict?
Loop over items and reassign? I'd expect something like:
result = {}
for k, v in d.items():
result[v] = kThat's the long form, and it works. But it's a textbook case for a dict comprehension — swap k and v positions in the output and you have a one-liner:
def invert_dict(d: dict) -> dict:
return {v: k for k, v in d.items()}.items() gives you each pair as (key, value); the comprehension unpacks them as k, v. Swapping their position inverts the mapping.
What if two original keys have the same value? Like {1: "alex", 2: "alex"} — two IDs mapping to the same username?
After inversion they'd collide: {"alex": ???}. Dict comprehensions let later writes win, so you'd end up with {"alex": 2} — the second ID overwrites the first. If that's not what you want, you need a different data shape (a dict mapping value to a list of keys). For this lesson, the test data has unique values, so the swap is clean.
And the values need to be hashable to become keys? Strings and ints work, but lists wouldn't?
Right. Dict keys must be hashable. Inverting a {str: str} dict gives another {str: str} — always safe. Inverting {str: list} raises TypeError because lists are unhashable. In practice, you'll mostly invert dicts of simple scalar values.
So anywhere I need a reverse lookup — IDs from names, codes from labels — this one-liner does it.
That's the pattern. Any time you built a dict one way and now need to look up the other way, invert instead of rebuilding from source data. It's also the foundation of "enum → name" and "name → enum" lookups in configuration code.
TL;DR: {v: k for k, v in d.items()} swaps keys and values in one expression.
.items() — yields (key, value) pairs for iteration{v: k ...} instead of {k: v ...}| Original | Inverted |
|---|---|
{1: "alex"} | {"alex": 1} |
{"a": 1, "b": 2} | {1: "a", 2: "b"} |
{} | {} |
The core move — swap k and v positions in the comprehension output.
You have a dict mapping user IDs to usernames — {1: "alex", 2: "blair", 3: "casey"} — and you want the opposite lookup: username to ID. {"alex": 1, "blair": 2, "casey": 3}. How do you invert a dict?
Loop over items and reassign? I'd expect something like:
result = {}
for k, v in d.items():
result[v] = kThat's the long form, and it works. But it's a textbook case for a dict comprehension — swap k and v positions in the output and you have a one-liner:
def invert_dict(d: dict) -> dict:
return {v: k for k, v in d.items()}.items() gives you each pair as (key, value); the comprehension unpacks them as k, v. Swapping their position inverts the mapping.
What if two original keys have the same value? Like {1: "alex", 2: "alex"} — two IDs mapping to the same username?
After inversion they'd collide: {"alex": ???}. Dict comprehensions let later writes win, so you'd end up with {"alex": 2} — the second ID overwrites the first. If that's not what you want, you need a different data shape (a dict mapping value to a list of keys). For this lesson, the test data has unique values, so the swap is clean.
And the values need to be hashable to become keys? Strings and ints work, but lists wouldn't?
Right. Dict keys must be hashable. Inverting a {str: str} dict gives another {str: str} — always safe. Inverting {str: list} raises TypeError because lists are unhashable. In practice, you'll mostly invert dicts of simple scalar values.
So anywhere I need a reverse lookup — IDs from names, codes from labels — this one-liner does it.
That's the pattern. Any time you built a dict one way and now need to look up the other way, invert instead of rebuilding from source data. It's also the foundation of "enum → name" and "name → enum" lookups in configuration code.
TL;DR: {v: k for k, v in d.items()} swaps keys and values in one expression.
.items() — yields (key, value) pairs for iteration{v: k ...} instead of {k: v ...}| Original | Inverted |
|---|---|
{1: "alex"} | {"alex": 1} |
{"a": 1, "b": 2} | {1: "a", 2: "b"} |
{} | {} |
The core move — swap k and v positions in the comprehension output.
Write `invert_dict(d)` that returns a new dict with keys and values swapped. Assume values are unique and hashable. Use a dict comprehension.
Tap each step for scaffolded hints.
No blank-editor panic.