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 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
data = [( 'sravan' , 23 ), ( 'ojaswi' , 15 ),
( 'rohith' , 8 ), ( 'gnanesh' , 4 ), ( 'bobby' , 20 )]
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
data = [( 'sravan' , 23 ), ( 'ojaswi' , 15 ),
( 'rohith' , 8 ), ( 'gnanesh' , 4 ), ( 'bobby' , 20 )]
dict ([(key, value) for key, value in data])
|
Output:
{'bobby': 20, 'gnanesh': 4, 'ojaswi': 15, 'rohith': 8, 'sravan': 23}
Method 2: Using zip() with dict() method
Here in this method, we will create two lists such that values in the first list will be the keys and the second list values will be the values in the dictionary.
Syntax: dict(zip(key_list,value_list))
Example 1:
Python3
name = [ 'sravan' , 'ojaswi' , 'rohith' , 'gnanesh' , 'bobby' ]
age = [ 23 , 21 , 32 , 11 , 23 ]
dict ( zip (name, age))
|
Output:
{'bobby': 23, 'gnanesh': 11, 'ojaswi': 21, 'rohith': 32, 'sravan': 23}
Method 3: Using Iterable
Here we can iterate over the given date using iterable for loop.
Syntax: {key: value for (key, value) in data}
Example:
Python3
data = [( 'sravan' , 23 ), ( 'ojaswi' , 15 ),
( 'rohith' , 8 ), ( 'gnanesh' , 4 ), ( 'bobby' , 20 )]
{key: value for (key, value) in data}
|
Output:
{'bobby': 20, 'gnanesh': 4, 'ojaswi': 15, 'rohith': 8, 'sravan': 23}
Method 4: Add Filter
We can add a filter to the iterable to a list comprehension to create a dictionary only for particular data based on condition. Filtering means adding values to dictionary-based on conditions.
Syntax: {key: value for (key, value) in data condition}
Example:
Python3
data = [( 'sravan' , 23 ), ( 'ojaswi' , 15 ),
( 'rohith' , 8 ), ( 'gnanesh' , 4 ), ( 'bobby' , 20 )]
print ({key: value for (key, value) in data if value = = 20 })
print ({key: value for (key, value) in data if value > 10 })
print ({key: value for (key, value) in data if key = = 'sravan' })
|
Output:
{'bobby': 20}
{'sravan': 23, 'ojaswi': 15, 'bobby': 20}
{'sravan': 23}
Last Updated :
02 Dec, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...