The Wayback Machine - https://web.archive.org/web/20250101230349/https://www.geeksforgeeks.org/python-dictionary-comprehension/
Open In App

Python Dictionary Comprehension

Last Updated : 25 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Like List Comprehension, Python allows dictionary comprehensions. We can create dictionaries using simple expressions. A dictionary comprehension takes the form {key: value for (key, value) in iterable}

Python Dictionary Comprehension Example

Here we have two lists named keys and value and we are iterating over them with the help of zip() function.

Python
# Python code to demonstrate dictionary 
# comprehension

# Lists to represent keys and values
keys = ['a','b','c','d','e']
values = [1,2,3,4,5]  

# but this line shows dict comprehension here  
myDict = { k:v for (k,v) in zip(keys, values)}  

# We can use below too
# myDict = dict(zip(keys, values))  

print (myDict)

Output :

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

Using fromkeys() Method

Here we are using the fromkeys() method that returns a dictionary with specific keys and values.

Python
dic=dict.fromkeys(range(5), True)

print(dic)

Output:

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

Using dictionary comprehension make dictionary

Example 1:

Python
# Python code to demonstrate dictionary 
# creation using list comprehension
myDict = {x: x**2 for x in [1,2,3,4,5]}
print (myDict)

Output :

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

Example 2:

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

Output :

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

Using conditional statements in dictionary comprehension

Example 1:

We can use Dictionary comprehensions with if and else statements and with other expressions too. This example below maps the numbers to their cubes that are divisible by 4.

Python
# Python code to demonstrate dictionary 
# comprehension using if.
newdict = {x: x**3 for x in range(10) if x**3 % 4 == 0}
print(newdict)

Output :

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

Using nested dictionary comprehension

Here we are trying to create a nested dictionary with the help of dictionary comprehension.

Python
# given string
l="GFG"

# using dictionary comprehension
dic = {
    x: {y: x + y for y in l} for x in l
}

print(dic)

Output:

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

Python Dictionary Comprehension – FAQs

What is Dictionary Comprehension in Python?

Dictionary comprehension in Python is a concise way to create dictionaries. It allows you to generate a dictionary from an iterable in a single line of code using a similar syntax to list comprehensions.

How to Create Dictionaries Using Comprehension in Python?

You can create dictionaries using dictionary comprehension by specifying an expression followed by a for loop inside curly braces {}.

Basic Syntax:

{key_expression: value_expression for item in iterable}

Example:

# Creating a dictionary with squares of numbers
squares = {x: x**2 for x in range(5)}
print(squares) # Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

What Are Benefits of Using Dictionary Comprehension in Python?

  1. Conciseness: Allows creating dictionaries in a single line of code, making the code more compact.
  2. Readability: Makes it easier to understand the intent of the code by reducing the boilerplate code.
  3. Performance: Generally faster than using traditional for loops due to optimization by the interpreter.
  4. Functional Programming Style: Aligns with the functional programming style and makes the code look cleaner.

How to Implement Complex Dictionary Comprehensions in Python?

Dictionary comprehensions can include conditional logic to filter elements or modify the key-value pairs based on certain conditions.

Example with Condition:

# Creating a dictionary with even numbers and their squares
even_squares = {x: x**2 for x in range(10) if x % 2 == 0}
print(even_squares) # Output: {0: 0, 2: 4, 4: 16, 6: 36, 8: 64}

Example with Nested Loops:

# Creating a dictionary with pairs of numbers and their products
products = {(x, y): x * y for x in range(1, 4) for y in range(1, 4)}
print(products)
# Output: {(1, 1): 1, (1, 2): 2, (1, 3): 3, (2, 1): 2, (2, 2): 4, (2, 3): 6, (3, 1): 3, (3, 2): 6, (3, 3): 9}

How Do Dictionary Comprehensions Enhance Code Readability in Python?

  1. Clear Intent: The intent of creating a dictionary is clear and straightforward.
  2. Less Boilerplate: Reduces the amount of code needed to create dictionaries, making it easier to read and maintain.
  3. Consistency: Consistent with other comprehensions in Python (list and set comprehensions), making it easier for Python developers to understand and use.
  4. Inline Logic: Allows embedding logic directly within the comprehension, making the code more readable and expressive.

Example Comparison:

Using a For Loop:

squares = {}
for x in range(5):
squares[x] = x**2
print(squares) # Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

Using Dictionary Comprehension:

squares = {x: x**2 for x in range(5)}
print(squares) # Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}


Next Article
Article Tags :
Practice Tags :

Similar Reads

three90RightbarBannerImg