0
0
Pythonprogramming~5 mins

Basic dictionary comprehension in Python

Choose your learning style9 modes available
Introduction

Dictionary comprehension helps you create new dictionaries quickly and clearly from existing data.

You want to make a new dictionary from a list of items.
You need to change keys or values in a dictionary easily.
You want to filter items while creating a dictionary.
You want to write less code to build dictionaries.
You want to transform data into a dictionary format.
Syntax
Python
{key_expression: value_expression for item in iterable}

The key_expression and value_expression define what each key and value will be.

The iterable can be a list, dictionary, or any collection you want to loop over.

Examples
This creates a dictionary where keys are numbers and values are double those numbers.
Python
{x: x * 2 for x in [1, 2, 3]}
This makes a dictionary with words as keys and their lengths as values.
Python
{word: len(word) for word in ['cat', 'dog', 'bird']}
This changes all values in the dictionary to uppercase.
Python
{k: v.upper() for k, v in {'a': 'apple', 'b': 'banana'}.items()}
Sample Program

This program creates 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

You can add conditions inside dictionary comprehensions to filter items.

Dictionary comprehensions are faster and cleaner than using loops to build dictionaries.

Summary

Dictionary comprehension is a quick way to create dictionaries from collections.

It uses a simple syntax with key and value expressions inside curly braces.

You can transform and filter data easily while creating dictionaries.