Course contentsShow
← Python
Lesson 278 of 1,0605. Advanced Iteration and ComprehensionsFree lesson

Creating Dictionary and Set Comprehensions

You will be able to apply the comprehension syntax patterns to efficiently construct sets and dictionaries from existing iterable data sources.

Streamlining Data Structures with Comprehensions

In this lesson, you will learn how to use the concise comprehension syntax to build dictionaries and sets directly from existing iterables.

By now, you are familiar with list comprehensions for creating lists efficiently. Python extends this powerful pattern to dictionaries and sets, allowing you to transform data into these structures in a single, readable line.

Dictionary Comprehensions

A dictionary comprehension uses curly braces {} and a colon : to define the relationship between keys and values. The syntax follows this pattern: {key_expression: value_expression for item in iterable}.

Imagine you have a list of fruit names and you want to create a dictionary mapping each name to its character length:

fruits = ["apple", "banana", "cherry"]
fruit_lengths = {fruit: len(fruit) for fruit in fruits}
# Result: {'apple': 5, 'banana': 6, 'cherry': 6}

This replaces a multi-line for loop that would otherwise require initializing an empty dictionary and manually assigning each key-value pair.

Set Comprehensions

Set comprehensions use the same curly brace syntax as dictionaries but omit the colon, as they only store unique elements. The syntax is: {expression for item in iterable}.

If you have a collection of numbers and want to extract only the unique squares of the even numbers, you can combine the comprehension with a conditional filter:

numbers = [1, 2, 2, 3, 4, 4, 5]
unique_even_squares = {n**2 for n in numbers if n % 2 == 0}
# Result: {4, 16}

Because sets automatically handle uniqueness, any duplicate results from your calculation are discarded immediately. This is far more efficient than creating a list and converting it to a set afterward.

Both techniques maintain the clarity of your code while leveraging the underlying performance of Python's optimized loop structures. Just like list comprehensions, remember to keep your expressions simple to ensure your code remains easy for others to read.

Key Takeaway: Use curly braces {} to create dictionaries with the key: value syntax or sets with a single expression, providing a clean and efficient alternative to manual initialization loops.