Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
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'} Advertisements
