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.

Similar Reads

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....

Method 2: Using zip() with dict() method

...

Method 3: Using Iterable

...

Method 4: Add Filter

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....