How to use dict() method In Python
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 as the value in the dictionary.
Syntax: dict(list_comprehension)
Example 1: Python program to create a student list comprehension and convert it into a dictionary.
Python3
# create a list comprehension with student age data = [( 'sravan' , 23 ), ( 'ojaswi' , 15 ), ( 'rohith' , 8 ), ( 'gnanesh' , 4 ), ( 'bobby' , 20 )] # using dict method dict (data) |
Output:
{'bobby': 20, 'gnanesh': 4, 'ojaswi': 15, 'rohith': 8, 'sravan': 23}
We can also use the following for loop inside the dict() method.
Syntax: dict([(key,value) for key,value in data])
Example 2:
Python3
# create a list comprehension with student age data = [( 'sravan' , 23 ), ( 'ojaswi' , 15 ), ( 'rohith' , 8 ), ( 'gnanesh' , 4 ), ( 'bobby' , 20 )] # using dict method inside for loop dict ([(key, value) for key, value in data]) |
Output:
{'bobby': 20, 'gnanesh': 4, 'ojaswi': 15, 'rohith': 8, 'sravan': 23}
Create a dictionary with list comprehension in Python
In this article, we will discuss how to create a dictionary with list comprehension in Python.