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
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
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
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
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
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
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
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
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
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
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
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
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
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
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.
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.
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.
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.
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.
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.
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.
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.
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.
Technical and placement interview questions
Frequently tested interview questions with detailed, full answers (click to expand)
Q1:What is a dictionary comprehension?
Q2:What is a set comprehension?
Q3:How do dictionary and set comprehensions differ?
Q4:What happens when a dictionary comprehension generates duplicate keys?
Q5:Why might you use sorted() with a set comprehension?
Q6:Can dictionary and set comprehensions contain conditions?
Q7:What does Python do when a set comprehension tries to insert an unhashable element?
Q8:When should you use a list instead of a set comprehension?
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.
Related Topics & Next Steps
4 Recommended LessonsStrengthen your Python foundation with these complementary core lessons: