In the last few posts, we’ve seen how powerful list comprehensions are for creating new lists in a single, readable line (Post #120, Post #121, Post #122). This concise syntax is so useful and “Pythonic” that the language provides a similar structure for its other main collection types: sets and dictionaries.
In this post, we’ll extend the concept of comprehensions to create sets and dictionaries, allowing us to build these data structures with the same elegance.
Set Comprehensions
A set comprehension works just like a list comprehension, but it creates a set instead of a list. The syntax is nearly identical—you just use curly braces {}
instead of square brackets []
.
The syntax is: {expression for item in iterable}
The key feature to remember is that because the result is a set, any duplicate values produced by the expression will be automatically and efficiently discarded.
Let’s say we have a list of numbers with duplicates, and we want to create a set of their unique squares.
numbers = [1, 2, 2, 3, 3, 3, 4]
# A set comprehension automatically handles duplicates
unique_squares = {number ** 2 for number in numbers}
print(unique_squares)
The output will be a set containing only the unique squared values:
{1, 4, 9, 16}
This is a very concise way to perform a transformation and a deduplication in a single step.
Dictionary Comprehensions
A dictionary comprehension also uses curly braces, but it requires you to specify both a key and a value, separated by a colon, for each item in the iterable.
The syntax is: {key_expression: value_expression for item in iterable}
We got a sneak peek of this in Post #72, but let’s formally review it. It’s a fantastic way to build a dictionary from another data source. For example, let’s create a dictionary that maps a number to its square.
numbers = [1, 2, 3, 4]
# The key is 'number' and the value is 'number ** 2'
squares_dict = {number: number ** 2 for number in numbers}
print(squares_dict)
The output is a dictionary: {1: 1, 2: 4, 3: 9, 4: 16}
.
Dictionary comprehensions are also great for transforming existing dictionaries. A classic example is swapping the keys and values.
original_dict = {"name": "Alice", "role": "Admin"}
# We use .items() to access both keys and values from the original dict
swapped_dict = {value: key for key, value in original_dict.items()}
print(f"Original: {original_dict}")
print(f"Swapped: {swapped_dict}")
The result is a new dictionary with the keys and values flipped:
Original: {'name': 'Alice', 'role': 'Admin'}
Swapped: {'Alice': 'name', 'Admin': 'role'}
What’s Next?
You can now use the concise comprehension syntax to build not only lists, but also sets and dictionaries. A set comprehension {expr for...}
is great for creating a set of unique values, while a dictionary comprehension {key: val for...}
is perfect for building a new dictionary from an existing iterable.
Comprehensions are a powerful and often beautiful feature of Python. It can be tempting to use them everywhere. However, their conciseness can sometimes come at the cost of readability, especially when the logic gets complex. In Post #124, we will discuss when not to use a comprehension and why a traditional for
loop is sometimes the better choice.
Author

Experienced Cloud & DevOps Engineer with hands-on experience in AWS, GCP, Terraform, Ansible, ELK, Docker, Git, GitLab, Python, PowerShell, Shell, and theoretical knowledge on Azure, Kubernetes & Jenkins. In my free time, I write blogs on ckdbtech.com