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
keys = ['a','b','c','d','e']
values = [1,2,3,4,5]
myDict = { k:v for (k,v) in 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
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
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
l="GFG"
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'}}
Don't miss your chance to ride the wave of the data revolution! Every industry is scaling new heights by tapping into the power of data. Sharpen your skills and become a part of the hottest trend in the 21st century.
Dive into the future of technology - explore the Complete Machine Learning and Data Science Program by GeeksforGeeks and stay ahead of the curve.
Commit to GfG's Three-90 Challenge! Purchase a course, complete 90% in 90 days, and save 90% cost click here to explore.
Last Updated :
30 Sep, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...