DEV Community

Max
Max

Posted on • Edited on

Python dictionaries comprehension tutorial

Python dictionaries comprehension is a way to create new dictionaries by specifying the key-value pairs using a single expression. This is similar to list comprehension, but instead of creating a list, we create a dictionary.

The general syntax for creating a dictionary using comprehension is:

{key_expression: value_expression for expression in iterable}
Enter fullscreen mode Exit fullscreen mode

Here, key_expression and value_expression are the expressions that generate the keys and values of the dictionary. expression is a variable that iterates over the iterable object.

Let's see two examples of Python dictionary comprehension to understand it better.

Example 1: Creating a dictionary of squares of numbers

squares = {num: num**2 for num in range(1, 6)}
print(squares)
Enter fullscreen mode Exit fullscreen mode

Output:

{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Enter fullscreen mode Exit fullscreen mode

In this example, we have created a dictionary squares using dictionary comprehension that contains the squares of numbers from 1 to 5. The key_expression is num, the value_expression is num**2, and the iterable is the range object from 1 to 6 (excluding 6).

Example 2: Creating a dictionary from a list

fruits = ['apple', 'banana', 'orange', 'kiwi', 'grape']
fruit_dict = {fruit: len(fruit) for fruit in fruits}
print(fruit_dict)
Enter fullscreen mode Exit fullscreen mode

Output:

{'apple': 5, 'banana': 6, 'orange': 6, 'kiwi': 4, 'grape': 5}
Enter fullscreen mode Exit fullscreen mode

In this example, we have created a dictionary fruit_dict using dictionary comprehension that contains the length of each fruit name in the list fruits. The key_expression is fruit, the value_expression is len(fruit), and the iterable is the fruits list.

Using dictionary comprehension, we can create dictionaries easily and quickly in a single line of code, making our code more concise and readable

Explore Other Related Articles

Python comparison between normal for loop and enumerate
Python if-else Statements Tutorial
Python set tutorial
Python tuple tutorial
Python Lists tutorial

Top comments (0)