We have a lot of variations and applications of dictionary container in Python and sometimes, we wish to perform a filter of keys in dictionary, i.e extracting just the keys which are present in particular container. Let’s discuss certain ways in which this can be performed. Method #1 : Using dictionary comprehension + items() This problem can be performed by reconstruction using the keys extracted through items function that wish to be filtered and dictionary function makes the desired dictionary.
Python3
test_dict = { 'nikhil' : 1 , "akash" : 2 , 'akshat' : 3 , 'manjeet' : 4 }
print ("The original dictionary : " + str (test_dict))
res = {key: test_dict[key] for key in test_dict.keys()
& { 'akshat' , 'nikhil' }}
print ("The filtered dictionary is : " + str (res))
|
Output : The original dictionary : {'manjeet': 4, 'akshat': 3, 'akash': 2, 'nikhil': 1}
The filtered dictionary is : {'akshat': 3, 'nikhil': 1}
Method #2 : Using dict() The dict function can be used to perform this task by converting the logic performed using list comprehension into a dictionary.
Python3
test_dict = { 'nikhil' : 1 , "akash" : 2 , 'akshat' : 3 , 'manjeet' : 4 }
print ("The original dictionary : " + str (test_dict))
res = dict ((k, test_dict[k]) for k in [ 'nikhil' , 'akshat' ]
if k in test_dict)
print ("The filtered dictionary is : " + str (res))
|
C++
#include <iostream>
using namespace std;
int main() {
cout<< "GFG!" ;
return 0;
}
|
Output : The original dictionary : {'manjeet': 4, 'akshat': 3, 'akash': 2, 'nikhil': 1}
The filtered dictionary is : {'akshat': 3, 'nikhil': 1}