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
# create a list comprehension with student age data = [( 'sravan' , 23 ), ( 'ojaswi' , 15 ), ( 'rohith' , 8 ), ( 'gnanesh' , 4 ), ( 'bobby' , 20 )] # create a dictionary with list # comprehension if value is equal to 20 print ({key: value for (key, value) in data if value = = 20 }) # create a dictionary with list # comprehension if value is greater than to 10 print ({key: value for (key, value) in data if value > 10 }) # create a dictionary with list # comprehension if key is sravan print ({key: value for (key, value) in data if key = = 'sravan' }) |
Output:
{'bobby': 20} {'sravan': 23, 'ojaswi': 15, 'bobby': 20} {'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.