Dict and Set Comprehensions
Learn how to build dictionaries and sets in a single line using comprehension syntax — a natural extension of the list comprehension skills you already have.
You've used list comprehensions to build lists in one line. Python has the same syntax for dicts and sets.
Dict comprehension syntax compared to list comprehension:
Here, we build a dict that maps each fruit to its length:
You can pair two lists using zip() inside a dict comprehension:
What will be the output?
Add an if clause after the loop to keep only items that match a condition.
Filter to only include words longer than 3 characters:
What will be the output?
Set comprehensions look like dict comprehensions but use a single expression. The result is a set, so duplicates are removed automatically.
Set comprehension syntax:
Get the set of unique lengths from a list of words:
What will be the output?
Set comprehensions also support filtering with an if clause:
What will be the output?
What will be the output?
What will be the output?