Python Dictionary Comprehension

Last Updated : 10 Jan, 2026

Dictionary comprehension is used to create a dictionary in a short and clear way. It allows keys and values to be generated from a loop in one line. This helps in building dictionaries directly without writing multiple statements.

Example: This example creates a dictionary where numbers from 1 to 5 are used as keys and their squares are stored as values.

Python
sq = {x: x**2 for x in range(1, 6)}
print(sq)

Output
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

Explanation:

  • x takes values from 1 to 5 and x becomes the key
  • x**2 becomes the value
  • Each key and value pair is added to the dictionary in one line

Syntax

{key: value for (key, value) in iterable if condition}

  • key: The item to use as the dictionary key.
  • value: The item to use as the dictionary value.
  • iterable: Any sequence or collection to loop through.
  • condition (optional): Lets you include only certain items

Creating a Dictionary from Two Lists

This method creates a dictionary by pairing each item from one list with the matching item from another list using zip().

Python
keys = ['a','b','c','d','e']
values = [1, 2, 3, 4, 5]  

d = {k:v for (k,v) in zip(keys, values)}  
print (d)

Output
{'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4}

Using fromkeys() Method

The fromkeys() method creates a dictionary by taking a group of keys and assigning the same value to all of them.

Python
d = dict.fromkeys(range(5), True)
print(d)

Output
{0: True, 1: True, 2: True, 3: True, 4: True}

Examples

Example 1: This example demonstrates creating a dictionary by transforming and repeating characters from a string.

Python
b = {x.upper(): x*3 for x in 'coding'}
print(b)

Output
{'C': 'ccc', 'O': 'ooo', 'D': 'ddd', 'I': 'iii', 'N': 'nnn', 'G': 'ggg'}


Example 2: This example maps a list of fruits to their name lengths

Python
c = {fruit: len(fruit) for fruit in ['apple', 'banana', 'cherry']}
print(c)

Output
{'apple': 5, 'banana': 6, 'cherry': 6}

Dictionary Comprehension with Conditional Statements

We can include conditions in a dictionary comprehension to filter items or apply logic only to specific values. This allows us to create dictionaries more selectively.

Python
d = {x: x**3 for x in range(10) if x**3 % 4 == 0}
print(d)

Output
{0: 0, 8: 512, 2: 8, 4: 64, 6: 216}

Nested Dictionary Comprehension

We can also create dictionaries within dictionaries using nested dictionary comprehensions. This is useful when each key maps to another dictionary of related values.

Python
s = "GF"
res = {x: {y: x + y for y in s} for x in s}
print(res)

Output
{'G': {'G': 'GG', 'F': 'GF'}, 'F': {'G': 'FG', 'F': 'FF'}}
Comment
Article Tags:

Explore