Lesson explanation
By the end of this lesson, you can:
In the previous lesson, a list comprehension created a list from an iterable. Dictionary comprehensions use curly braces with a key: value pair:
new_dict = {key_expression: value_expression for item in source}Use .items() to process dictionary keys and values together; add a trailing if to exclude entries. A dictionary keeps one value per key. If multiple input entries produce the same key, the later result replaces the earlier value. The source collection is not changed.
A set comprehension also uses curly braces, but has no colon:
new_set = {expression for item in source}Sets retain unique values, but their iteration order is not guaranteed. When output needs a predictable order, sort the resulting set before printing or returning it as a list. As with list comprehensions, choose a regular loop if the transformation has several steps or side effects.
Choose a key and a derived value for each item:
packages = ["api", "worker", "mailer"]
name_lengths = {package: len(package) for package in packages}
print(name_lengths)Output:
{'api': 3, 'worker': 6, 'mailer': 6}Every package becomes a key; its length becomes the value.
Use .items() to access both parts of each entry:
balances = {"ops": 55, "research": 20, "support": 80}
raised = {team: amount + 10 for team, amount in balances.items() if amount >= 50}
print(raised)Output:
{'ops': 65, 'support': 90}The research entry is excluded, and the original dictionary still contains its original values.
A set comprehension keeps each distinct cleaned label once:
raw_labels = [" Backend ", "backend", "DATA", "data "]
labels = {value.strip().lower() for value in raw_labels}
print(sorted(labels))Output:
['backend', 'data']We use sorted() for predictable display—not because the set itself has a sorted order.
When different values generate the same key, the later assignment wins:
entries = ["DEV", "dev", "Test"]
last_seen = {name.lower(): name for name in entries}
print(last_seen)Output:
{'dev': 'dev', 'test': 'Test'}Both first entries generate dev; the later original value overwrites the earlier one.
| Intent | Syntax |
|---|---|
| Dictionary from items | {key: value for item in source} |
| Filter dictionary | {k: v for k, v in source.items() if condition} |
| Set of unique values | {expression for item in source} |
| Predictable display | sorted(your_set) |
if filters come after the for part, not before it.{} for a dictionary or set() for a set.