
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Python Extract specific keys from dictionary?
Dictionaries are most extensively used data structures in python. They contain data in form of keys and values. In this example we will see how to get the items form a dictionary specific to a given set of keys.
With dictionary comprehension
In this approach we simply loop through the dictionary using a for loop with in operator. But along with the in operator we also mention the values of the keys when referring to the dictionary keys.
Example
dictA = {'Sun': '2 PM', "Tue": '5 PM', 'Wed': '3 PM', 'Fri': '9 PM'} # Given dictionary print("Given dictionary : ",dictA) res = {key: dictA[key] for key in dictA.keys() & {'Fri', 'Sun'}} # Result print("Dictionary with given keys is : ",res)
Output
Running the above code gives us the following result −
Given dictionary : {'Sun': '2 PM', 'Tue': '5 PM', 'Wed': '3 PM', 'Fri': '9 PM'} Dictionary with given keys is : {'Fri': '9 PM', 'Sun': '2 PM'}
With dict()
In this approach we choose the required keys of the dictionary while passing on the keys to the dict() function. Alogn with using a for loop.
Example
dictA = {'Sun': '2 PM', "Tue": '5 PM', 'Wed': '3 PM', 'Fri': '9 PM'} # Given dictionary print("Given dictionary : ",dictA) res = dict((k, dictA[k]) for k in ['Fri', 'Wed'] if k in dictA) # Result print("Dictionary with given keys is : ",res)
Output
Running the above code gives us the following result −
Given dictionary : {'Sun': '2 PM', 'Tue': '5 PM', 'Wed': '3 PM', 'Fri': '9 PM'} Dictionary with given keys is : {'Fri': '9 PM', 'Wed': '3 PM'}
- Related Articles
- Python – Filter immutable rows representing Dictionary Keys from Matrix
- Properties of Dictionary Keys in Python
- Python - Cumulative Mean of Dictionary keys
- How to create Python dictionary from list of keys and values?
- How does Python dictionary keys() Method work?
- Python dictionary with keys having multiple inputs
- Append Dictionary Keys and Values (In order ) in dictionary using Python
- Extract Unique dictionary values in Python Program
- How to extract subset of key-value pairs from Python dictionary object?
- How to get a list of all the keys from a Python dictionary?
- How to create Python dictionary with duplicate keys?
- Get dictionary keys as a list in Python
- Keys associated with Values in Dictionary in Python
- Why must dictionary keys be immutable in Python?
- Python Pandas - Extract the minute from DateTimeIndex with specific time series frequency

Advertisements