Dictionary comprehension is a concise way to create dictionaries in Python. It allows us to create a new dictionary by performing operations on existing iterables, such as lists or other dictionaries. Dictionary comprehension is similar to [list comprehension](/tutorials/list-comprehension), but instead of creating lists, it creates dictionaries.
The basic syntax of dictionary comprehension consists of curly braces `{}` enclosing an expression that defines both the key and value of each item in the dictionary, followed by a `for` loop to iterate over the elements of an iterable object. Here's an example:
numbers = [1, 2, 3, 4, 5]
squared_numbers = {x: x**2 for x in numbers}
In this example, we use dictionary comprehension to create a new dictionary called `squared_numbers`. The expression `x: x**2` defines both the key and value of each item in the dictionary. The `for` loop iterates over each element `x` in the `numbers` list.
The resulting `squared_numbers` dictionary will contain the original numbers as keys and their squared values as values: `{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}`.
Dictionary comprehension can also include conditional statements to filter the elements that are included in the new dictionary. Here's an example:
numbers = [1, 2, 3, 4, 5]
even_numbers = {x: x**2 for x in numbers if x % 2 == 0}
In this code, we use dictionary comprehension to create a new dictionary called `even_numbers`. The expression `x: x**2` defines the key-value pairs of each item in the dictionary. The `for` loop iterates over each element `x` in the `numbers` list, and the condition `x % 2 == 0` checks if the number is even.
The resulting `even_numbers` dictionary will contain only the even numbers from the original list as keys, with their squared values as values: `{2: 4, 4: 16}`.
Dictionary comprehension is a concise and efficient way to create dictionaries based on existing iterables. It can be used to transform, filter, or combine elements from one or more iterables into a dictionary.