Concept
Dictionary Comprehensions
Build new dictionaries in one line using `{key_expr: val_expr for item in iterable}`.
python
names = ["alice", "bob"]
lengths = {n: len(n) for n in names}
print(lengths) # {'alice': 5, 'bob': 3}
# 101. Dictionary Comprehensions Build new dictionaries in one line using `{key_expr: val_expr for item in iterable}`: ```python names = ["alice", "bob"] lengths = {n: len(n) for n in names} print(lengths) # {'alice': 5, 'bob': 3} ``` Notice the colon `:` between `n` and `len(n)`. Without that colon, Python assumes you're writing a set comprehension and throws away your keys.
Checkpoint
In `{k: v for k, v in pairs}`, what creates a dictionary instead of a set?
Practice
Given `nums = [1, 2, 3]`, create a dictionary mapping each number `n` to its square `n * n` using a dictionary comprehension. Print the result.
01
Tap code blocks below to assemble
Available Blocks