Building Dicts the Short Way
The idea
Same concept as list and set comprehensions — but now you're building a dict.
Every element produces a key-value pair instead of just a value.
The syntax
{key_expr: value_expr for item in iterable}
Curly braces, a colon between key and value, the rest the same.
squares = {n: n ** 2 for n in range(1, 6)}
print(squares)
Output → {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
"For each n in range — key is n, value is n squared."
From a list — build a lookup dict
Turn a list of names into a dict with name lengths as values:
names = ["Raven", "Wolf", "Ghost", "Viper"]
lengths = {name: len(name) for name in names}
print(lengths)
Output → {'Raven': 5, 'Wolf': 4, 'Ghost': 5, 'Viper': 5}
Transform values in an existing dict
You have scores. You want to know if each soldier passed:
scores = {"Raven": 85, "Wolf": 74, "Ghost": 91}
status = {name: "passed" if score >= 80 else "failed"
for name, score in scores.items()}
print(status)
Output → {'Raven': 'passed', 'Wolf': 'failed', 'Ghost': 'passed'}
Filter key-value pairs
Keep only the passing scores:
scores = {"Raven": 85, "Wolf": 74, "Ghost": 91, "Viper": 63}
passing = {name: score for name, score in scores.items() if score >= 80}
print(passing)
Output → {'Raven': 85, 'Ghost': 91}
Swap keys and values
original = {"Raven": 85, "Wolf": 74, "Ghost": 91}
swapped = {score: name for name, score in original.items()}
print(swapped)
Output → {85: 'Raven', 74: 'Wolf', 91: 'Ghost'}
Only works cleanly when values are unique — duplicate values would overwrite each other.
From two lists
names = ["Raven", "Wolf", "Ghost"]
scores = [85, 74, 91]
result = {name: score for name, score in zip(names, scores)}
print(result)
Output → {'Raven': 85, 'Wolf': 74, 'Ghost': 91}
You saw dict(zip()) earlier — this is the comprehension version. Same result, more flexible.
Heads up!
- Keys must be unique — if the comprehension produces duplicate keys, last one wins
- Use
.items()when iterating over an existing dict - The
ifgoes at the end — after thefor - Swapping keys and values only works when all values are unique
What you should understand now
- Dict comprehension syntax:
{key: value for item in iterable} - Add a filter:
{key: value for item in iterable if condition} - Use
.items()to transform or filter an existing dict - Swap keys and values with
{v: k for k, v in d.items()} - Build from two lists with
zip()