Open In App
Related Articles

Python Dictionary Comprehension

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

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.

Python3

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 not 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.

Python3

# 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'}}


Last Updated : 30 Sep, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads