🚀 LEVEL UP TO SENIOR:Unlock 500+ Advanced Practical Challenges & Exercises.
🎓 COURSERA PARTNER:Earn professional Google, Meta, and IBM certificates to supercharge your resume.
REFERENCEpython

python Documentation

LOADING ENGINE...

Dictionary Comprehensions

AI & DATA SCIENCE // dictionary-comprehensions

A dictionary comprehension builds a new dict in a single expression, producing a key-value pair for each item of an iterable, with an optional filtering condition.

Syntax

{key_expr: value_expr for item in iterable if condition}

Deep Dive Course

A dict comprehension follows the same shape as a list comprehension, but produces key-value pairs instead of single values, using a colon to separate the key expression from the value expression. It's commonly used to transform an existing dict, like swapping keys and values or filtering entries, or to build a dict from two related sequences, such as pairing up a list of keys with a list of computed values.

1Understanding Dictionary Comprehensions

A dict comprehension follows the same shape as a list comprehension, but produces key-value pairs instead of single values, using a colon to separate the key expression from the value expression. It's commonly used to transform an existing dict, like swapping keys and values or filtering entries, or to build a dict from two related sequences, such as pairing up a list of keys with a list of computed values.

💡

Swapping a dict's keys and values with a comprehension only works cleanly if the original values are unique and hashable — if two keys share the same value, the swap silently loses one of them, since dict keys must be unique.

editor.html
names = ["Alice", "Bob", "Carol"]
name_lengths = {name: len(name) for name in names}
print(name_lengths)
localhost:3000

2Practical Example

Here is a real-world application of Dictionary Comprehensions showing how it is used in production Python code.

editor.html
prices = {"apple": 1.5, "banana": 0.5, "cherry": 3.0}
expensive = {item: price for item, price in prices.items() if price > 1}
print(expensive)
localhost:3000

3Best Practices

Follow these guidelines when working with Dictionary Comprehensions:

1. Use a dict comprehension instead of a for loop with manual key assignment when building a dict from a transformation of another iterable

2. Use it to filter an existing dict's entries by key or value, instead of manually building a new dict and copying matching entries over

3. Watch out for duplicate keys/values when transforming a dict with a comprehension — later entries silently overwrite earlier ones with the same key

⚠️

Tip: Swapping a dict's keys and values with a comprehension only works cleanly if the original values are unique and hashable — if two keys share the same value, the swap silently loses one of them, since dict keys must be unique.

editor.html
names = ["Alice", "Bob", "Carol"]
name_lengths = {name: len(name) for name in names}
print(name_lengths)
localhost:3000

Examples

Example 01Basic Usage
names = ["Alice", "Bob", "Carol"]
name_lengths = {name: len(name) for name in names}
print(name_lengths)
Example 02Advanced Example
prices = {"apple": 1.5, "banana": 0.5, "cherry": 3.0}
expensive = {item: price for item, price in prices.items() if price > 1}
print(expensive)

Best Practices

  • Use a dict comprehension instead of a for loop with manual key assignment when building a dict from a transformation of another iterable
  • Use it to filter an existing dict's entries by key or value, instead of manually building a new dict and copying matching entries over
  • Watch out for duplicate keys/values when transforming a dict with a comprehension — later entries silently overwrite earlier ones with the same key

Interview Question

What happens if you use a dict comprehension to swap the keys and values of a dict where two different keys share the same value?

Hint: Think about the constraint that dict keys must be unique.

Since dict keys must be unique, swapping key/value pairs means the original values become the new keys — if two original keys shared the same value, that value would appear twice as a key in the swapped result, which isn't allowed. Whichever pair is processed last during the comprehension silently overwrites the earlier one with the same new key, so information about the first key is lost without any warning or error.

Exercises

MediumPractice using Dictionary Comprehensions in a real scenario.
View Solution
names = ["Alice", "Bob", "Carol"]
name_lengths = {name: len(name) for name in names}
print(name_lengths)

Frequently Asked Questions

What happens if you use a dict comprehension to swap the keys and values of a dict where two different keys share the same value?

Since dict keys must be unique, swapping key/value pairs means the original values become the new keys — if two original keys shared the same value, that value would appear twice as a key in the swapped result, which isn't allowed. Whichever pair is processed last during the comprehension silently overwrites the earlier one with the same new key, so information about the first key is lost without any warning or error.

Related Functions

dictionarieslist-comprehensionszip()