Open In App

Python Dictionary Comprehension

Last Updated : 30 Sep, 2022
Improve
Improve
Like Article
Like
Save
Share
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'}}


Previous Article
Next Article

Similar Reads

Create a dictionary with list comprehension in Python
In this article, we will discuss how to create a dictionary with list comprehension in Python. Method 1: Using dict() method Using dict() method we can convert list comprehension to the dictionary. Here we will pass the list_comprehension like a list of tuple values such that the first value act as a key in the dictionary and the second value act a
3 min read
Count set bits using Python List comprehension
Write an efficient program to count number of 1s in binary representation of an integer. Examples: Input : n = 6 Output : 2 Binary representation of 6 is 110 and has 2 set bits Input : n = 11 Output : 3 Binary representation of 11 is 1101 and has 3 set bits We have existing solution for this problem please refer Count set bits in an integer link. W
2 min read
Python List Comprehension to find pair with given sum from two arrays
Given two unsorted arrays of distinct elements, the task is to find all pairs from both arrays whose sum is equal to x. Examples: Input : arr1 = [-1, -2, 4, -6, 5, 7] arr2 = [6, 3, 4, 0] x = 8 Output : [(5, 3), (4, 4)] Input : arr1 = [1, 2, 4, 5, 7] arr2 = [5, 6, 3, 4, 8] x = 9 Output : [(1, 8), (4, 5), (5, 4)] We have existing solution for this pr
2 min read
Python List Comprehension | Segregate 0's and 1's in an array list
You are given an array of 0s and 1s in random order. Segregate 0s on left side and 1s on right side of the array. Examples: Input : arr = [0, 1, 0, 1, 0, 0, 1, 1, 1, 0] Output : [0, 0, 0, 0, 0, 1, 1, 1, 1, 1] We have existing solution for this problem please refer Segregate 0s and 1s in an array link. We can solve this problem quickly in Python usi
2 min read
Python List Comprehension | Sort even-placed elements in increasing and odd-placed in decreasing order
We are given an array of n distinct numbers, the task is to sort all even-placed numbers in increasing and odd-place numbers in decreasing order. The modified array should contain all sorted even-placed numbers followed by reverse sorted odd-placed numbers. Note that the first element is considered as even because of its index 0. Examples: Input: a
2 min read
Python List Comprehension | Three way partitioning of an array around a given range
Given an array and a range [lowVal, highVal], partition the array around the range such that array is divided in three parts. 1) All elements smaller than lowVal come first. 2) All elements in range lowVal to highVal come next. 3) All elements greater than highVal appear in the end. The individual elements of three sets can appear in any order. Exa
3 min read
Difference between List comprehension and Lambda in Python
List comprehension is an elegant way to define and create a list in Python. We can create lists just like mathematical statements and in one line only. The syntax of list comprehension is easier to grasp. A list comprehension generally consists of these parts : Output expression,Input sequence,A variable representing a member of the input sequence
3 min read
Python | List comprehension vs * operator
* operator and range() in python 3.x has many uses. One of them is to initialize the list. Code : Initializing 1D-list list in Python # Python code to initialize 1D-list # Initialize using star operator # list of size 5 will be initialized. # star is used outside the list. list1 = [0]*5 # Initialize using list comprehension # list of size 5 will be
2 min read
Python - Map vs List comprehension
Suppose we have a function and we want to compute this function for different values in a single line of code . This is where map() function plays its role ! map() function returns a map object(which is an iterator) of the results after applying the given function to each item of a given iterable (list, tuple etc.) Syntax: map(funcname, iterables)
3 min read
How to handle a Python Exception in a List Comprehension?
An exception is something that interrupts the flow of the program. These exceptions stop the process running and sends out an error message. Exceptions can be simply viewed as an object that represents an error. There are predefined exceptions and user-defined exceptions in Python. In this article, we will discuss how to handle Python exception in
5 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg