Working With Iterables II

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:

Python

Here, we build a dict that maps each fruit to its length:

Python
Output

You can pair two lists using zip() inside a dict comprehension:

Python
Output

What will be the output?

Python

Add an if clause after the loop to keep only items that match a condition.

Filter to only include words longer than 3 characters:

Python
Output

What will be the output?

Python

Set comprehensions look like dict comprehensions but use a single expression. The result is a set, so duplicates are removed automatically.

Set comprehension syntax:

Python

Get the set of unique lengths from a list of words:

Python
Output

What will be the output?

Python

Set comprehensions also support filtering with an if clause:

Python
Output

What will be the output?

Python

What will be the output?

Python

What will be the output?

Python