VOOZH about

URL: https://www.geeksforgeeks.org/python/python-dictionary-comprehension/

⇱ Python Dictionary Comprehension - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Python Dictionary Comprehension

Last Updated : 18 Apr, 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.


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().


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.


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.


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


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.


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.


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

Related Articles:

Comment
Article Tags:
Article Tags: