What Is Dictionary Comprehension in Python?
What Is Dictionary Comprehension?
Dictionary comprehension is a feature in Python that allows us to build dictionaries in a single, elegant line of code. If you have worked with list comprehension before, this concept will feel familiar. The key difference is that instead of generating lists, dictionary comprehension generates key-value pairs.
Syntax of Dictionary Comprehension
Here’s the general syntax of dictionary comprehension:
{key_expression: value_expression for item in iterable if condition}
Let’s walk through the parameters of dictionary comprehension:
key_expression
: Determines each key in the dictionary.value_expression
: Defines the value associated with each key.if
(Optional): Filters which items are included in the dictionary.
Now that we know the syntax of dictionary comprehension let’s use it to create a dictionary.
Learn Swift: Arrays, Sets, and Dictionaries
Continue your Swift journey by learning these collection types: arrays, sets, and dictionaries! Try it for freeExamples of Dictionary Comprehension in Python
Example 1: Creating a Dictionary of Squares
Let’s create a dictionary where the keys are numbers from 1 to 5, and the values are their squares:
numbers = [1, 2, 3, 4, 5]squares = {n: n**2 for n in numbers}print(squares)
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Example 2: Filtering Even Numbers
Let’s create a dictionary where the keys are even numbers from 0 to 9, and the values are their squares. We achieve this by adding a condition to filter out odd numbers:
numbers = range(10)even_squares = {n: n**2 for n in numbers if n % 2 == 0}print(even_squares)
{0: 0, 2: 4, 4: 16, 6: 36, 8: 64}
Example 3: Transforming an Existing Dictionary
We can use dictionary comprehension to modify the values in an existing dictionary. For instance, let’s double all the values in a dictionary of key-value pairs:
original = {'a': 1, 'b': 2, 'c': 3}doubled = {key: value * 2 for key, value in original.items()}print(doubled)
Here, original.items()
loops through each key-value pair, multiplies each value by 2, and creates a new dictionary with the same keys but updated values.
{'a': 2, 'b': 4, 'c': 6}
This approach is great for making quick transformations.
Real-World Applications of Python Dictionary Comprehension
Python’s dictionary comprehension is versatile and widely applicable in real-world scenarios. Here are some examples:
Inverting a Dictionary
Inverting a dictionary means swapping the keys and values, so what used to be a key becomes a value, and what used to be a value becomes a key. It’s like flipping a map so you can find your way from the destination back to the starting point. Let’s explore this concept with the help of an example where we need to swap keys and values:
original = {'x': 1, 'y': 2, 'z': 3}inverted = {value: key for key, value in original.items()}print(inverted)
Here we have a dictionary that encodes letters as numbers {'x': 1, 'y': 2, 'z': 3}
, inverting it gives the following output.
{1: 'x', 2: 'y', 3: 'z'}
This technique is helpful when we need reverse lookups.
Combining Two Lists
Imagine we have two lists, one with labels (like column headers in a spreadsheet) and another with values (like the row data). When we combine them, it creates a dictionary, where each label is paired with its corresponding value. Let’s walkthrough an example to understand this:
keys = ['name', 'age', 'city']values = ['Alice', 25, 'Seattle']combined = {k: v for k, v in zip(keys, values)}print(combined)
In this example, one list has labels ['name', 'age', 'city']
and another list has values ['Alice', 25, 'Seattle']
. When we combine them, we get a dictionary:
{'name': 'Alice', 'age': 25, 'city': 'Seattle'}
Categorizing Numbers
Categorizing numbers means putting them into groups based on certain rules. It’s like sorting clothes into piles: socks in one pile, shirts in another, and pants in a third pile! Let’s understand this with the help of an example, where we label numbers as “even” or “odd”:
numbers = range(1, 6)labels = {n: 'even' if n % 2 == 0 else 'odd' for n in numbers}print(labels)
{1: 'odd', 2: 'even', 3: 'odd', 4: 'even', 5: 'odd'}
Why Should We Use Dictionary Comprehension?
Dictionary comprehension is useful for multiple reasons:
- Efficient Code: Write less code to achieve the same results.
- Improved Readability: Express our intent clearly and succinctly.
- Dynamic Data Handling: Filter or transform data while building dictionaries. Whether we’re creating new dictionaries or modifying existing ones, dictionary comprehension enhances our productivity and code quality.
Conclusion
Dictionary comprehension is a versatile and expressive tool in Python. By combining iteration, transformation, and filtering into a single statement, it allows us to create powerful, concise dictionaries.
Whether we’re cleaning data, performing lookups, or building mappings, dictionary comprehension is a technique that saves time and enhances code readability. Start experimenting with it today to unlock new possibilities in your Python projects!
For more in-depth Python tutorials, check out Codecademy’s Learn Python 3 course and enhance your programming skills further.
'The Codecademy Team, composed of experienced educators and tech experts, is dedicated to making tech skills accessible to all. We empower learners worldwide with expert-reviewed content that develops and enhances the technical skills needed to advance and succeed in their careers.'
Meet the full teamRelated articles
- Article
How to Sort a Dictionary by Key or Value in Python
Learn how to sort Python dictionaries by keys or values using built-in functions like `sorted()` and handle edge cases with `OrderedDict`. - Article
A Guide to Python Data Structures
Learn the fundamentals of Python data structures in this comprehensive guide, covering different types, examples, and ideal scenarios for using them efficiently. - Article
List Comprehensions
Learn about how to create new lists in one line of Python!
Learn more on Codecademy
- Free course
Learn Swift: Arrays, Sets, and Dictionaries
Continue your Swift journey by learning these collection types: arrays, sets, and dictionaries!Beginner Friendly4 hours - Course
Learn Python 3
Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.With CertificateBeginner Friendly23 hours - Free course
Python for Programmers
An introduction to the basic syntax and fundamentals of Python for experienced programmers.Intermediate3 hours