Skip to content
Home / Fundamentals

Create a Python dict with Comprehension

In Python, a dictionary is an unordered collection of data values that consists of key-value pairs. It is an efficient way to store and retrieve data, and it is often used to represent data in a more structured and organized way.

One way to create a dictionary in Python is using a dictionary comprehension, which is a concise way to create a dictionary using a single line of code. Dictionary comprehensions are similar to list comprehensions, but they are used to create dictionaries instead of lists.

Here is the general syntax for creating a dictionary with comprehension in Python:

dictionary = {key: value for key, value in iterable}

Let's look at some examples to understand how dictionary comprehensions work.

Example 1: Creating a dictionary with comprehension from a list of tuples

Suppose we have a list of tuples that represent the names and ages of a group of people. We can use a dictionary comprehension to create a dictionary that maps names to ages.

people = [("Alice", 30), ("Bob", 35), ("Charlie", 40)]
age_dict = {name: age for name, age in people}
print(age_dict)

The output of the code above will be:

{'Alice': 30, 'Bob': 35, 'Charlie': 40}

As you can see, the dictionary comprehension creates a dictionary that maps names to ages, using the tuples in the people list as the key-value pairs.

Example 2: Creating a dictionary with comprehension from a list of strings

Suppose we have a list of strings that represent the names of a group of people. We can use a dictionary comprehension to create a dictionary that maps names to the length of the names.

names = ["Alice", "Bob", "Charlie"]
length_dict = {name: len(name) for name in names}
print(length_dict)
{'Alice': 5, 'Bob': 3, 'Charlie': 7}

As you can see, the dictionary comprehension creates a dictionary that maps names to the length of the names, using the strings in the names list as the keys and the length of the strings as the values.

Example 3: Creating a dictionary with comprehension and a condition

We can also use a condition in a dictionary comprehension to filter the key-value pairs that are included in the dictionary.

For example, suppose we have a list of numbers and we want to create a dictionary that maps even numbers to their squares. We can use a dictionary comprehension with a condition to achieve this.

numbers = [1, 2, 3, 4, 5, 6]
even_squares_dict = {x: x**2 for x in numbers if x % 2 == 0}
print(even_squares_dict)

The output of the code above will be:

{2: 4, 4: 16, 6: 36}

As you can see, the dictionary comprehension creates a dictionary that maps even numbers to their squares, using only the even numbers in the numbers list as the keys and the squares of those numbers as the values.