0
0
Pythonprogramming~5 mins

Why dictionary comprehension is used in Python

Choose your learning style9 modes available
Introduction

Dictionary comprehension helps create dictionaries quickly and clearly in one line. It saves time and makes code easier to read.

When you want to create a new dictionary from a list or another dictionary.
When you need to change or filter keys and values while making a dictionary.
When you want to write shorter and cleaner code instead of using loops.
When you want to apply a simple rule to all items to make a dictionary.
When you want to avoid writing multiple lines for building dictionaries.
Syntax
Python
{key_expression: value_expression for item in iterable if condition}
The key_expression and value_expression define what each key and value will be.
The if condition part is optional and lets you include only some items.
Examples
Creates a dictionary with numbers 0 to 4 as keys and their squares as values.
Python
{x: x*x for x in range(5)}
Creates a dictionary of squares only for even numbers from 0 to 9.
Python
{x: x*x for x in range(10) if x % 2 == 0}
Creates a dictionary with words as keys and their lengths as values.
Python
{word: len(word) for word in ['apple', 'banana', 'cherry']}
Sample Program

This program makes a dictionary where each fruit name is a key and its length is the value.

Python
fruits = ['apple', 'banana', 'cherry']
lengths = {fruit: len(fruit) for fruit in fruits}
print(lengths)
OutputSuccess
Important Notes

Dictionary comprehension is faster and cleaner than using loops to build dictionaries.

Use it when the logic is simple; for complex cases, normal loops might be clearer.

Summary

Dictionary comprehension creates dictionaries quickly in one line.

It can include conditions to filter items.

It makes code shorter and easier to read.