Introduction
The Python dictionary comprehension is a concise and powerful way to create dictionaries form other iterable objects. It essentially does for dictionaries what a list comprehension does for lists. Because the dictionary comprehension syntax and usage is so similar to that of the list comprehension, the list comprehension lesson is a recommended prerequisite.
Basic Python Dictionary Comprehension Syntax
The basic syntax of a dictionary comprehension consists of curly braces {}
that surround two expressions separated by a colon :
, followed by for
loop-like syntax. Here’s the general structure of a Python dictionary comprehension:
{key_expression: value_expression for item in iterable}
key_expression
: An expression that produces the key for each key-value pair of the dictionary.value_expression
: An expression that produces the value for each key-value pair.item
: A variable that represents each item in the iterable.iterable
: The original iterable being operated on, from which key-value pairs will be processed. This can be any iterable object.
If you know this syntax and understand list comprehensions, then you have a good grasp on dictionary comprehensions.
Creating a Simple Dictionary With a Dictionary Comprehension
The following example demonstrates how to create a dictionary that maps numbers (the keys) to their squares (the values).
Example:
squares_dict = {x: x**2 for x in range(1, 6)} print(squares_dict)
Output:
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
In this example:
x: x**2
: The key-value pair expression that calculates the square of each number and maps it to the number itself.range(1, 6)
: An iterable that holds the numbers 1 to 5.for x in range(1, 6)
: Iterates through numbers from 1 to 5.
The resulting squares_dict
dictionary contains {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
.
Using if Clauses in Dictionary Comprehensions
Similar to list comprehensions, dictionary comprehensions can include an optional if
clause to filter key-value pairs based on a condition. The syntax for using an if
clause is as follows:
{key_expression: value_expression for item in iterable if condition}
condition
: A boolean expression that determines whether a key-value pair should be included in the new dictionary.
The following example uses an if
clause to filter even numbers and their squares into a dictionary.
Example:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] even_squares_dict = {x: x**2 for x in numbers if x % 2 == 0} print(even_squares_dict)
Output:
{2: 4, 4: 16, 6: 36, 8: 64, 10: 100}
In this example, the if x % 2 == 0
condition checks if a number is even. Only the even numbers and their squares from the numbers
list are included in the even_squares_dict
dictionary. The result is {2: 4, 4: 16, 6: 36, 8: 64, 10: 100}
.
Using if-else Ternary Expressions
Just like in list comprehensions, you can use ternary expressions within dictionary comprehensions to conditionally modify values based on a condition. The syntax for a ternary expression within a dictionary comprehension is as follows:
{key_expression: value_if_true if condition else value_if_false for item in iterable}
condition
: Determines which value will be used for the key-value pair.value_if_true
: Evaluated if the condition is true.value_if_false
: Evaluated if the condition is false.
The following example uses a ternary expression to create a dictionary that maps numbers to “even” or “odd” strings based on their parity.
Example:
numbers = [1, 2, 3, 4, 5] even_odd_dict = {x: "even" if x % 2 == 0 else "odd" for x in numbers} print(even_odd_dict)
Output:
{1: 'odd', 2: 'even', 3: 'odd', 4: 'even', 5: 'odd'}
Nested Dictionary Comprehensions
Nested dictionary comprehensions are also supported, which allow you to create dictionaries from nested iterables of iterables.
The basic syntax of a nested list comprehension is as follows:
[key_expression: value_expression for inner_iterable in outer_iterable for item in inner_iterable]
key_expression
: An expression that produces the key for each key-value pair of the dictionary.value_expression
: An expression that produces the value for each key-value pair.inner_iterable
: The variable that receives the inner iterables. For example, if you are processing a list of tuples, this variable will receive the individual tuples.outer_iterable
: This is the outer, overall iterable. If you are processing a list of tuples, this is the overall list itself.
The following example creates a dictionary that maps numbers (the keys) to their squares (the values) out of a numbers in a 2-dimensional list (a matrix).
Example:
matrix = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] squares_dict = {x:x**2 for row in matrix for x in row} print(squares_dict)
Output:
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100, 11: 121, 12: 144}
As with nested list comprehensions, it is possible to have more levels of nesting and if
conditions for each level as well. For more information on how to do this with comprehensions, please see the Nested List Comprehension section of the list comprehension lesson.
Summary & Reference for Python Dictionary Comprehensions
Dictionary comprehensions offer a concise and powerful way to create new dictionaries by applying expressions to elements in existing iterable objects.
The fundamental structure of dictionary comprehensions has curly braces {}
that surround a comma-separated key-value pair expression, followed by a for
loop-like format.
{key_expression: value_expression for item in iterable}
Here is an example that builds a dictionary of numbers (the keys) to their squares (the values):
squares_dict = {x: x**2 for x in range(1, 6)} # squares_dict --> {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Dictionary comprehensions can include if
clauses for filtering elements based on conditions.
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] even_squares_dict = {x: x**2 for x in numbers if x % 2 == 0} # even_squares_dict --> {2: 4, 4: 16, 6: 36, 8: 64, 10: 100}
Ternary expressions within dictionary comprehensions allow for conditional element modification.
numbers = [1, 2, 3, 4, 5] even_odd_dict = {x: "even" if x % 2 == 0 else "odd" for x in numbers} # even_odd_dict --> {1: 'odd', 2: 'even', 3: 'odd', 4: 'even', 5: 'odd'}
Python supports nested dictionary comprehensions for creating dictionaries from nested iterable of iterables structures.
matrix = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] squares_dict = {x: x**2 for row in matrix for x in row} # squares_dict --> {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100, 11: 121, 12: 144}
You can further nest dictionary comprehensions with multiple levels and incorporate if
clauses at each level.