A roster maps student names to the length of each name.
What You Need to Understand
A dictionary comprehension produces key-value pairs from an iterable in one expression. Keys are unique, so repeated generated keys overwrite earlier values.
When to Use It
A roster maps student names to the length of each name.
Step-by-Step Python Example
names = ["Maya", "Daniel", "Noa"]
name_lengths = {name: len(name) for name in names}
print(name_lengths)
How the Example Works
For every name, the expression creates one key and its computed length. The resulting dictionary can be looked up by name.
Example Output
{'Maya': 4, 'Daniel': 6, 'Noa': 3}
{1: 1, 2: 4, 3: 9, 4: 16}
A Second Example
Compare this smaller variation with the main example, then experiment with your own values.
print({number: number * number for number in range(1, 5)})
Important Behavior and Edge Cases
The key expression must produce a hashable value. For complex transformations, use a normal loop so the logic stays visible.
Try It Yourself
Generate a dictionary mapping integers 1 through 4 to their squares.
Common Beginner Mistakes
- The key expression must produce a hashable value. For complex transformations, use a normal loop so the logic stays visible.
- Treating missing dictionary keys, replacement precedence, and shallow copies as if they had identical behavior in every context.
Key Takeaways
- A dictionary comprehension produces key-value pairs from an iterable in one expression.
- For every name, the expression creates one key and its computed length.
- The key expression must produce a hashable value.