Python – Extract Keys with specific Value Type
Last Updated :
22 Apr, 2023
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.
Similar Reads
Get specific keys' values - Python
Our task is to retrieve values associated with specific keys from a dictionary. This is especially useful when we only need to access certain pieces of data rather than the entire dictionary. For example, suppose we have the following dictionary: d = {'name': 'John', 'age': 25, 'location': 'New York
3 min read
Python - Extract Item with Maximum Tuple Value
Sometimes, while working with Python dictionaries, we can have a problem in which we need to extract the item with maximum value of value tuple index. This kind of problem can have application in domains such as web development. Let's discuss certain ways in which this task can be performed. Input :
5 min read
Python - Remove Keys with K value
We are given a dictionary we need to remove the keys with K value. For example, we are having a dictionary d = {'a': 1, 'b': 2, 'c': 1, 'd': 3} we need to remove the keys which is having K value so that the output should be {'b': 2, 'd': 3} . We can use dictionary comprehension and many other method
4 min read
Python - Extract Unique value key pairs
Sometimes, while working on Python dictionaries, we can have a problem in which we need to perform the extraction of selected pairs of keys from dictionary list, that too unique. This kind of problem can have application in many domains including day-day programming. Let's discuss certain ways in wh
5 min read
Python | Extract specific keys from dictionary
We have a lot of variations and applications of dictionary containers in Python and sometimes, we wish to perform a filter of keys in a dictionary, i.e extracting just the keys which are present in the particular container. Let's discuss certain ways in which this can be performed. Extract specific
4 min read
Python - Find Keys with specific suffix in Dictionary
Sometimes, while working with dictionaries, we can have a problem in which we need to find the dictionary items that have some constraints on keys. One such constraint can be a suffix match on keys. Letâs discuss certain ways in which this task can be performed. Method #1 : Using dictionary comprehe
6 min read
Python - Extracting Key from Value Substring
Sometimes, while working with Python dictionaries, we can have a problem in which we need to find the key from given value, querying substring from key's value. This kind of problem is common and have application in many domains including web development. Lets discuss certain ways in which this task
5 min read
Python - Remove keys with substring values
Sometimes, we need to remove keys whose values contain a specific substring. For example, consider the dictionary d = {'name1': 'hello world', 'name2': 'python code', 'name3': 'world peace'}. If we want to remove keys where the value contains the substring 'world', the resulting dictionary should ex
3 min read
Python - Extracting keys not in values
Sometimes, while working with Python dictionaries, we can have a problem in which we require to get all the keys that do not occur in values lists. This can have applications in the domains such as day-day programming. Lets discuss certain ways in which this task can be performed. Method #1 : Using
5 min read
Python - Extract dictionaries with Empty String value in K key
Given a List of dictionaries, extract all the dictionaries which have empty strings as values of a particular key. Input : test_list = [{"Gfg" : "4", "is" : "good", "best" : "1"}, {"Gfg" : "9", "is" : "CS", "best" : "10"}], K = "Gfg" Output : [] Explanation : No "Gfg" key is empty. Input : test_list
8 min read