Skip to content
PythonComprehensions and Functional Patternsbeginner25 min read

Dictionary and Set Comprehensions

Build dictionaries from key-value expressions and sets of unique values using concise, readable Python comprehensions.

In this lesson, you will learn

  • ✓Explain the purpose and syntax of dictionary and set comprehensions.
  • ✓Create dictionaries by calculating keys and values from an iterable.
  • ✓Create sets of unique values and explain how duplicates are handled.
  • ✓Use conditions to filter items in dictionary and set comprehensions.
  • ✓Predict the result of comprehensions, including duplicate keys, empty inputs, and duplicate set elements.
  • ✓Distinguish dictionaries from sets and choose the appropriate structure for a task.

1. Dictionary comprehensions: create key-value pairs

A dictionary stores key-value pairs. Each key identifies a value, allowing you to look up information by key rather than by position.

A dictionary comprehension builds a dictionary from an iterable. Its general syntax is {key_expression: value_expression for item in iterable}. For each item, Python evaluates the key expression and the value expression, then adds the resulting pair to the dictionary.

The colon separates the key expression from the value expression. This is what distinguishes a dictionary comprehension from a set comprehension.

Dictionary keys must be hashable. Common examples include strings, integers, and tuples containing hashable values. Lists and dictionaries cannot be used as dictionary keys.

Use a dictionary comprehension when the keys and values can be calculated clearly from each input item. It is especially useful for creating lookup tables, converting values, and building mappings from existing data.

Map numbers to their squares

Map numbers to their squares
python
squares = {n: n * n for n in range(1, 4)}
print(squares)
Output
{1: 1, 2: 4, 3: 9}

range(1, 4) produces 1, 2, and 3. For each number, n becomes the key and n * n becomes its value. The resulting dictionary maps 1 to 1, 2 to 4, and 3 to 9. The expression before the colon calculates the key; the expression after the colon calculates the value.

Note

A dictionary comprehension creates a new dictionary. Unless you explicitly assign into or modify the original dictionary, the original mapping remains unchanged.

2. Set comprehensions: create unique values

A set is a collection of distinct hashable elements. Adding the same value more than once does not create multiple copies in the set.

A set comprehension uses the syntax {expression for item in iterable}. Unlike a dictionary comprehension, it has no key-value colon. Each iteration produces one candidate set element.

Python automatically removes duplicate elements according to equality and hashing rules. This makes set comprehensions useful for collecting unique lengths, distinct categories, unique normalized strings, or other non-repeating values.

A set is unordered. Do not rely on the order in which its elements are displayed. If a predictable ascending order is required for numeric or otherwise mutually comparable values, use sorted() to produce a list.

Create a set of unique word lengths

Create a set of unique word lengths
python
words = ['cat', 'dog', 'owl', 'elephant']
lengths = {len(word) for word in words}
print(sorted(lengths))
Output
[3, 8]

The comprehension calculates the length of each word. Cat, dog, and owl each have length 3; elephant has length 8. The set stores 3 only once even though three words have that length. sorted(lengths) returns a list in ascending order, so the displayed output is predictable.

Caution

A set is not a sorted list. Its displayed order is not guaranteed. Use sorted() when you need ordered output and the elements can be compared with one another.

3. Dictionary versus set comprehensions

Both forms use braces, but their contents determine the type of collection they create. A key-value expression containing a colon creates a dictionary. A single element expression creates a set.

Choose a dictionary when each key must be associated with a value, such as a product and its price. Choose a set when you only need distinct values, such as the unique lengths of words.

A dictionary comprehension can also have duplicate keys in its input. If a later iteration produces a key that already exists, the later value replaces the previous value for that key. This differs from a set, where repeated equal elements are retained only once.

An empty dictionary is written as {}, while an empty set is written as set(). The expression {} does not create an empty set; it creates an empty dictionary.

Compare the two forms

Compare the two forms
python
numbers = [1, 2, 3]
squares = {n: n * n for n in numbers}
unique_squares = {n * n for n in numbers}
print(squares)
print(sorted(unique_squares))
Output
{1: 1, 2: 4, 3: 9} [1, 4, 9]

The dictionary comprehension stores each number as a key and its square as the value. The set comprehension stores only the square values. The dictionary provides a mapping from input number to calculated value. The set provides distinct square values without preserving the association with the original numbers.

Note

Ask what information the result must preserve. If you need a key-to-value relationship, use a dictionary. If you only need distinct elements, use a set.

4. Add conditions to dictionary and set comprehensions

Dictionary and set comprehensions can include an if filter after the iterable clause, just like list comprehensions.

The condition determines which input items are processed. In a dictionary comprehension, accepted items produce key-value pairs. In a set comprehension, accepted items produce set elements.

You can combine filtering with transformation. For example, a dictionary comprehension can select only passing scores and map each student's name to their score. A set comprehension can select only positive values and keep their distinct squares.

The filter does not replace a rejected item. If the condition is false, that iteration contributes no dictionary entry or set element.

Dictionary of passing scores

Dictionary of passing scores
python
scores = {'Asha': 82, 'Ravi': 45, 'Mina': 91, 'Kabir': 38}
passed = {name: score for name, score in scores.items() if score >= 50}
print(passed)
Output
{'Asha': 82, 'Mina': 91}

The items() method provides each student's name and score. The filter score >= 50 accepts scores of at least 50. Asha and Mina meet the requirement; Ravi and Kabir do not. The resulting dictionary retains each passing student's name and score.

Caution

Put the filter after the iterable clause. For example, {n: n * n for n in numbers if n > 0} is a dictionary comprehension that excludes non-positive values.

5. Trace comprehensions step by step

When a comprehension is difficult to trace, evaluate one input item at a time. Identify the item, check any condition, calculate the output expression, and determine how the resulting value enters the collection.

For dictionary comprehensions, keep track of both the key and value. If a key already exists, the new value replaces the previous value associated with that key.

For set comprehensions, track the elements already collected. A new value is added only if it is not already represented in the set.

The following examples show why tracing the actual expression is more reliable than assuming that every input produces a separate result.

Trace a dictionary comprehension

Trace a dictionary comprehension
python
numbers = [2, 3, 4]
result = {n: n + 10 for n in numbers if n > 2}
print(result)
Output
{3: 13, 4: 14}

For n = 2, the condition 2 > 2 is false, so no entry is created. For n = 3, the condition is true, producing the key-value pair 3: 13. For n = 4, the condition is true, producing the key-value pair 4: 14. The completed dictionary contains the two accepted entries.

Note

A comprehension processes the iterable in its iteration order, but a set does not promise a particular display order. Use sorted() when a stable ordered result is needed and the elements are comparable.

6. Edge cases and choosing the right collection

An empty iterable produces an empty collection because there are no items to process. This is valid behavior rather than an error.

Duplicate set values are removed automatically. Duplicate dictionary keys are not stored as separate entries; the later value replaces the earlier value for that key.

Set elements and dictionary keys must be hashable. A tuple containing only hashable elements can be used as a key or set element, but a list cannot.

A dictionary comprehension should produce meaningful keys. If the key expression repeatedly produces the same key, the resulting dictionary may contain fewer entries than the input.

Use a set comprehension when uniqueness is the goal. Use a dictionary comprehension when the result needs a relationship between each key and its value. If you need repeated values or must preserve every occurrence, a list comprehension may be more appropriate.

Empty input

Empty input
python
numbers = []
squares = {n: n * n for n in numbers}
unique_squares = {n * n for n in numbers}
print(squares)
print(unique_squares)
Output
{} set()

The input list is empty, so neither comprehension processes an item. The dictionary comprehension produces an empty dictionary. The set comprehension produces an empty set. Python displays an empty set as set(), not {}.

Caution

Do not assume every iterable element can be used directly as a dictionary key or set element. If a value is unhashable, Python raises TypeError when the comprehension attempts to insert it.

7. Practical examples and readability

Dictionary and set comprehensions are most useful when the collection can be created using a clear expression and an optional filter.

A dictionary comprehension can build a lookup table, calculate transformed values, or select a subset of a mapping. A set comprehension can collect distinct normalized strings, categories, or calculated values.

Avoid making a comprehension so complex that its purpose becomes difficult to explain. A regular loop may be easier to maintain when the logic involves several dependent operations, complicated branching, or error handling.

Build a lookup table

Build a lookup table
python
names = ['Asha', 'Ravi', 'Mina']
name_lengths = {name: len(name) for name in names}
print(name_lengths)
print(name_lengths['Mina'])
Output
{'Asha': 4, 'Ravi': 4, 'Mina': 4} 4

Each name is a key, and its length is the associated value. The dictionary can be used for later lookups by name. Accessing name_lengths['Mina'] retrieves the value associated with the key 'Mina'.

Note

Choose the data structure according to the requirement: dictionaries associate keys with values, sets retain distinct elements, and lists retain order and repeated occurrences.

Common pitfalls to avoid

Real debugging lessons and exact syntax contrasts to avoid runtime bugs

#1 Using a colon in a set comprehension when no key-value mapping is needed.

Why it happens: A colon creates key:value pairs for a dictionary comprehension; a set comprehension contains only the element expression.

Incorrect Approach
script.py
python
Using a colon in a set comprehension when no key-value mapping is needed.
Correct Solution
script.py
python
Use {expression for item in iterable} for a set and {key_expression: value_expression for item in iterable} for a dictionary.

Key takeaway: Use {expression for item in iterable} for a set and {key_expression: value_expression for item in iterable} for a dictionary.

#2 Assuming a set comprehension preserves input order.

Why it happens: Sets represent unique values and do not guarantee a meaningful iteration order; sort the result when stable display order matters.

Incorrect Approach
script.py
python
Assuming a set comprehension preserves input order.
Correct Solution
script.py
python
Sets do not guarantee iteration or display order. Use sorted() when you need an ordered result and the elements are comparable.

Key takeaway: Sets do not guarantee iteration or display order. Use sorted() when you need an ordered result and the elements are comparable.

#3 Expecting duplicate set elements to appear multiple times.

Why it happens: Repeated equal values collapse into one set element by design.

Incorrect Approach
script.py
python
Expecting duplicate set elements to appear multiple times.
Correct Solution
script.py
python
Sets store distinct elements. Equal values are represented only once.

Key takeaway: Sets store distinct elements. Equal values are represented only once.

#4 Expecting a dictionary to store multiple values for the same key automatically.

Why it happens: Dictionary keys are unique, so a repeated key updates the value associated with that key rather than storing another independent entry.

Incorrect Approach
script.py
python
Expecting a dictionary to store multiple values for the same key automatically.
Correct Solution
script.py
python
A dictionary has one value per key. If a comprehension generates the same key repeatedly, the later value replaces the earlier one.

Key takeaway: A dictionary has one value per key. If a comprehension generates the same key repeatedly, the later value replaces the earlier one.

#5 Using {} to create an empty set.

Why it happens: The literal {} creates an empty dictionary; use set() for an empty set.

Incorrect Approach
script.py
python
Using {} to create an empty set.
Correct Solution
script.py
python
Use set() for an empty set. Empty braces, {}, create an empty dictionary.

Key takeaway: Use set() for an empty set. Empty braces, {}, create an empty dictionary.

#6 Using a list as a dictionary key or set element.

Why it happens: Lists are mutable and unhashable, so they cannot be used as dictionary keys or set elements.

Incorrect Approach
script.py
python
Using a list as a dictionary key or set element.
Correct Solution
script.py
python
Keys and set elements must be hashable. Convert a list to a tuple when its contents are hashable and a tuple is appropriate for the task.

Key takeaway: Keys and set elements must be hashable. Convert a list to a tuple when its contents are hashable and a tuple is appropriate for the task.

#7 Forgetting that the if clause filters input items.

Why it happens: The if clause in a comprehension filters which input items contribute to the result.

Incorrect Approach
script.py
python
Forgetting that the if clause filters input items.
Correct Solution
script.py
python
A false filter condition means that iteration contributes no entry or element. Put the condition after the iterable clause.

Key takeaway: A false filter condition means that iteration contributes no entry or element. Put the condition after the iterable clause.

#8 Choosing a set when duplicate values or every occurrence must be preserved.

Why it happens: A set removes duplicates, so use a list when order or repeated occurrences must be preserved.

Incorrect Approach
script.py
python
Choosing a set when duplicate values or every occurrence must be preserved.
Correct Solution
script.py
python
Use a list when order and repeated occurrences matter. Use a set only when uniqueness is part of the requirement.

Key takeaway: Use a list when order and repeated occurrences matter. Use a set only when uniqueness is part of the requirement.

Ready for hands-on challenges?

Test your skills with shuffled coding challenges in the Practice Arena.

Practice Arena →

Technical and placement interview questions

Frequently tested interview questions with detailed, full answers (click to expand)

Q1:What is a dictionary comprehension?
Answer:
A dictionary comprehension is a concise way to construct a dictionary from an iterable. It uses a key expression and a value expression, as in {n: n * n for n in range(1, 4)}. It can also include a filter to select which entries are created.
Q2:What is a set comprehension?
Answer:
A set comprehension constructs a set from an iterable using the syntax {expression for item in iterable}. The result contains distinct hashable elements. Repeated equal values do not create separate set elements.
Q3:How do dictionary and set comprehensions differ?
Answer:
A dictionary comprehension contains key-value expressions separated by a colon and preserves the relationship between each key and its value. A set comprehension contains a single element expression and collects unique values.
Q4:What happens when a dictionary comprehension generates duplicate keys?
Answer:
The dictionary retains one entry for that key, and the later value replaces the earlier value. If every generated key is unique, the result can contain one entry for every processed input item.
Q5:Why might you use sorted() with a set comprehension?
Answer:
Sets do not guarantee a particular iteration or display order. sorted() returns a list in ascending order when the elements can be compared, making examples and output easier to reproduce.
Q6:Can dictionary and set comprehensions contain conditions?
Answer:
Yes. A filter can follow the iterable clause. For example, {n: n * n for n in numbers if n > 0} creates dictionary entries only for positive numbers, while {n * n for n in numbers if n > 0} creates a set of their distinct squares.
Q7:What does Python do when a set comprehension tries to insert an unhashable element?
Answer:
Python raises TypeError. For example, lists cannot be stored directly in a set. If appropriate, a list can be converted to a tuple whose elements are all hashable.
Q8:When should you use a list instead of a set comprehension?
Answer:
Use a list comprehension when the order of the input items and repeated occurrences need to be retained. Use a set comprehension when the goal is to collect distinct values, and use a dictionary comprehension when key-value relationships are needed.

Key takeaways

  • Dictionary comprehensions use {key_expression: value_expression for item in iterable}.
  • Set comprehensions use {expression for item in iterable}.
  • A dictionary stores key-value relationships, while a set stores distinct elements.
  • Duplicate dictionary keys cause later values to replace earlier values for those keys.
  • Duplicate equal set elements are represented only once.
  • Use an if filter to control which input items contribute to the result.
  • Use sorted() when you need a predictable ordered result from a set and its elements are comparable.
  • An empty dictionary is {}, while an empty set is set().
  • Dictionary keys and set elements must be hashable.
  • Choose the collection based on whether the task needs mappings, unique values, or an ordered sequence with possible duplicates.
Was this lesson helpful?
Found an error? Report an issue

Related Topics & Next Steps

4 Recommended Lessons

Strengthen your Python foundation with these complementary core lessons: