
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Filter Dictionary Keys Based on Values in Selective List in Python
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
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
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']
Advertisements