Python – Extract Keys with specific Value Type
Given a dictionary, extract all the keys, whose values are of a given type.
Input : test_dict = {‘gfg’ : 2, ‘is’ : ‘hello’, ‘for’ : {‘1’ : 3}, ‘geeks’ : 4}, targ_type = int
Output : [‘gfg’, ‘geeks’]
Explanation : gfg and geeks have integer values.
Input : test_dict = {‘gfg’ : 2, ‘is’ : ‘hello’, ‘for’ : {‘1’ : 3}, ‘geeks’ : 4}, targ_type = str
Output : [‘is’]
Explanation : is has string value.
Method #1 : Using loop + isinstance()
In this, we check for data type using isinstance(), and iterate for all the values using the loop.
Python3
test_dict = { 'gfg' : 2 , 'is' : 'hello' , 'best' : 2 , 'for' : { '1' : 3 }, 'geeks' : 4 }
print ( "The original dictionary is : " + str (test_dict))
targ_type = int
res = []
for key, val in test_dict.items():
if isinstance (val, targ_type):
res.append(key)
print ( "The extracted keys : " + str (res))
|
Output
The original dictionary is : {'gfg': 2, 'is': 'hello', 'best': 2, 'for': {'1': 3}, 'geeks': 4}
The extracted keys : ['gfg', 'best', 'geeks']
The time complexity of this code is O(n), where n is the number of key-value pairs in the dictionary, as it iterates through each key-value pair exactly once.
The space complexity of this code is O(m), where m is the number of keys that have the target value type, as it creates a list to store the keys that match the target value type. In the worst case scenario where all keys have the target value type, the space complexity would be O(n).
Method #2 : Using list comprehension + isinstance()
Similar to above method, one-liner shorthand to solve this problem using list comprehension.
Python3
test_dict = { 'gfg' : 2 , 'is' : 'hello' , 'best' : 2 , 'for' : { '1' : 3 }, 'geeks' : 4 }
print ( "The original dictionary is : " + str (test_dict))
targ_type = int
res = [key for key, val in test_dict.items() if isinstance (val, targ_type)]
print ( "The extracted keys : " + str (res))
|
Output
The original dictionary is : {'gfg': 2, 'is': 'hello', 'best': 2, 'for': {'1': 3}, 'geeks': 4}
The extracted keys : ['gfg', 'best', 'geeks']
Method #3: Using keys() and type() methods
Python3
test_dict = { 'gfg' : 2 , 'is' : 'hello' , 'best' : 2 , 'for' : { '1' : 3 }, 'geeks' : 4 }
print ( "The original dictionary is : " + str (test_dict))
targ_type = int
res = []
for i in test_dict.keys():
if type (test_dict[i]) is targ_type:
res.append(i)
print ( "The extracted keys : " + str (res))
|
Output
The original dictionary is : {'gfg': 2, 'is': 'hello', 'best': 2, 'for': {'1': 3}, 'geeks': 4}
The extracted keys : ['gfg', 'best', 'geeks']
Method#4:Using dictionary Comprehension
Algorithm
- Initialize the dictionary test_dict.
- Initialize the variable targ_type with the data type to be extracted.
- Create an empty list res to store the extracted keys.
- Loop through all the keys in the dictionary using a for loop.
- Use the type() function to check if the value of the key is of the specified data type.
- If the value of the key is of the specified data type, append the key to the res list.
- Print the res list with the extracted keys.
Python3
test_dict = { 'gfg' : 2 , 'is' : 'hello' , 'best' : 2 , 'for' : { '1' : 3 }, 'geeks' : 4 }
print ( "The original dictionary is : " + str (test_dict))
targ_type = int
res = [key for key, value in test_dict.items() if isinstance (value, targ_type)]
print ( "The extracted keys : " + str (res))
|
Output
The original dictionary is : {'gfg': 2, 'is': 'hello', 'best': 2, 'for': {'1': 3}, 'geeks': 4}
The extracted keys : ['gfg', 'best', 'geeks']
Time Complexity: O(n) Looping through all the keys of the dictionary takes linear time.
Auxiliary Space: O(k) The space occupied by the res list increases with the number of keys that have values of the specified data type.
Method 5: using the filter() function
Approach:
- Initialize the dictionary test_dict with keys and values.
- Print the original dictionary using the print() function and concatenate the string with str(test_dict).
- Initialize the target type targ_type to int.
- Use the filter() function to extract keys from test_dict based on the target type targ_type. The filter() function takes two arguments:
- A lambda function that checks whether the value of each key is of the target type targ_type.
- The keys of test_dict to filter.
- The list() function is used to convert the filter object returned by filter() into a list of keys.
- Print the extracted keys using the print() function and concatenating the string with str(res).
Python3
test_dict = { 'gfg' : 2 , 'is' : 'hello' , 'best' : 2 , 'for' : { '1' : 3 }, 'geeks' : 4 }
print ( "The original dictionary is : " + str (test_dict))
targ_type = int
res = list ( filter ( lambda x: isinstance (
test_dict[x], targ_type), test_dict.keys()))
print ( "The extracted keys : " + str (res))
|
Output
The original dictionary is : {'gfg': 2, 'is': 'hello', 'best': 2, 'for': {'1': 3}, 'geeks': 4}
The extracted keys : ['gfg', 'best', 'geeks']
Time Complexity of the filter() function is O(n), where n is the number of elements in the dictionary.
Auxiliary Space complexity is also O(n), as we are storing the filtered keys in a list.
Method 6: using reduce():
- Import the reduce() method from the functools module.
- Define a dictionary test_dict.
- Pass a lambda function to reduce() that takes three parameters: acc, x, and test_dict. acc is an accumulator variable that stores the list of keys with integer values encountered so far, x is the current key being processed, and test_dict is the original dictionary.
- Check if the value associated with the current key x is an integer using the isinstance() method. If it is, the lambda function adds that key x to the accumulator acc as a list, otherwise it simply returns acc.
- Pass the keys of the dictionary as the second argument to reduce().
- Start with an initial value of an empty list [] for the accumulator.
- Store the result of reduce() in the variable res.
- Print the original dictionary and the list of extracted keys.
Python3
from functools import reduce
test_dict = { 'gfg' : 2 , 'is' : 'hello' , 'best' : 2 , 'for' : { '1' : 3 }, 'geeks' : 4 }
res = reduce ( lambda acc, x: acc +
[x] if isinstance (test_dict[x], int ) else acc, test_dict.keys(), [])
print ( "The original dictionary is : " + str (test_dict))
print ( "The extracted keys : " + str (res))
|
Output
The original dictionary is : {'gfg': 2, 'is': 'hello', 'best': 2, 'for': {'1': 3}, 'geeks': 4}
The extracted keys : ['gfg', 'best', 'geeks']
Time complexity: O(n), where n is the number of keys in the dictionary. This is because the method applies the lambda function to each key in the dictionary exactly once.
Space Complexity: O(n), where n is the number of keys in the dictionary. This is because the method creates a list to store the extracted keys, whose length can be at most n. Additionally, the lambda function only stores the current key being processed and the accumulator variable, which take constant space.
Last Updated :
22 Apr, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...