Python - Filter dictionary key based on the values in selective list


Sometimes in a Python dictionary we may need to to filter out certain keys of the dictionary based on certain criteria. In this article we will see how to filter out keys from Python dictionary.

With for and in

In this approach we put the values of the keys to be filtered in a list. Then iterate through each element of the list and check for its presence in the given dictionary. We create a resulting dictionary containing these values which are found in the dictionary.

Example

 Live Demo

dictA= {'Mon':'Phy','Tue':'chem','Wed':'Math','Thu':'Bio'}
key_list = ['Tue','Thu']

print("Given Dictionary:\n",dictA)
print("Keys for filter:\n",key_list)
res = [dictA[i] for i in key_list if i in dictA]

print("Dictionary with filtered keys:\n",res)

Output

Running the above code gives us the following result −

Given Dictionary:
   {'Mon': 'Phy', 'Tue': 'chem', 'Wed': 'Math', 'Thu': 'Bio'}
Keys for filter:
   ['Tue', 'Thu']
Dictionary with filtered keys:
   ['chem', 'Bio']

With intersection

We use intersection to find the common elements between the given dictionary and the list. Then apply the set function to get the distinct elements and convert the result to a list.

Example

 Live Demo

dictA= {'Mon':'Phy','Tue':'chem','Wed':'Math','Thu':'Bio'}
key_list = ['Tue','Thu']

print("Given Dictionary:\n",dictA)
print("Keys for filter:\n",key_list)

temp = list(set(key_list).intersection(dictA))

res = [dictA[i] for i in temp]

print("Dictionary with filtered keys:\n",res)

Output

Running the above code gives us the following result −

Given Dictionary:
   {'Mon': 'Phy', 'Tue': 'chem', 'Wed': 'Math', 'Thu': 'Bio'}
Keys for filter:
   ['Tue', 'Thu']
Dictionary with filtered keys:
   ['chem', 'Bio']

Updated on: 22-Jul-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements