Sunday, December 29, 2024
Google search engine
HomeLanguagesPython – Extract Keys with specific Value Type

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}, ‘neveropen’ : 4}, targ_type = int 
Output : [‘gfg’, ‘neveropen’] 
Explanation : gfg andneveropen have integer values.

Input : test_dict = {‘gfg’ : 2, ‘is’ : ‘hello’, ‘for’ : {‘1’ : 3}, ‘neveropen’ : 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




# Python3 code to demonstrate working of
# Extract Keys with specific Value Type
# Using loop + isinstance()
 
# initializing dictionary
test_dict = {'gfg': 2, 'is': 'hello', 'best': 2, 'for': {'1': 3}, 'neveropen': 4}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# initializing type
targ_type = int
 
res = []
for key, val in test_dict.items():
 
    # checking for values datatype
    if isinstance(val, targ_type):
        res.append(key)
 
# printing result
print("The extracted keys : " + str(res))


Output

The original dictionary is : {'gfg': 2, 'is': 'hello', 'best': 2, 'for': {'1': 3}, 'neveropen': 4}
The extracted keys : ['gfg', 'best', 'neveropen']

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




# Python3 code to demonstrate working of
# Extract Keys with specific Value Type
# Using list comprehension + isinstance()
 
# initializing dictionary
test_dict = {'gfg': 2, 'is': 'hello', 'best': 2, 'for': {'1': 3}, 'neveropen': 4}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# initializing type
targ_type = int
 
# one-liner to solve the problem
res = [key for key, val in test_dict.items() if isinstance(val, targ_type)]
 
# printing result
print("The extracted keys : " + str(res))


Output

The original dictionary is : {'gfg': 2, 'is': 'hello', 'best': 2, 'for': {'1': 3}, 'neveropen': 4}
The extracted keys : ['gfg', 'best', 'neveropen']

Method #3: Using keys() and type() methods

Python3




# Python3 code to demonstrate working of
# Extract Keys with specific Value Type
 
# initializing dictionary
test_dict = {'gfg': 2, 'is': 'hello', 'best': 2, 'for': {'1': 3}, 'neveropen': 4}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# initializing type
targ_type = int
res=[]
for i in test_dict.keys():
    if type(test_dict[i]) is targ_type:
        res.append(i)
# printing result
print("The extracted keys : " + str(res))


Output

The original dictionary is : {'gfg': 2, 'is': 'hello', 'best': 2, 'for': {'1': 3}, 'neveropen': 4}
The extracted keys : ['gfg', 'best', 'neveropen']

Method#4:Using dictionary Comprehension

Algorithm

  1. Initialize the dictionary test_dict.
  2. Initialize the variable targ_type with the data type to be extracted.
  3. Create an empty list res to store the extracted keys.
  4. Loop through all the keys in the dictionary using a for loop.
  5. Use the type() function to check if the value of the key is of the specified data type.
  6. If the value of the key is of the specified data type, append the key to the res list.
  7. Print the res list with the extracted keys.

Python3




# initializing dictionary
test_dict = {'gfg': 2, 'is': 'hello', 'best': 2, 'for': {'1': 3}, 'neveropen': 4}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# initializing type
targ_type = int
 
# using dictionary comprehension to extract keys
res = [key for key, value in test_dict.items() if isinstance(value, targ_type)]
 
# printing result
print("The extracted keys : " + str(res))
#This code is contributed by Vinay Pinjala.


Output

The original dictionary is : {'gfg': 2, 'is': 'hello', 'best': 2, 'for': {'1': 3}, 'neveropen': 4}
The extracted keys : ['gfg', 'best', 'neveropen']

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:

  1. Initialize the dictionary test_dict with keys and values.
  2. Print the original dictionary using the print() function and concatenate the string with str(test_dict).
  3. Initialize the target type targ_type to int.
  4. Use the filter() function to extract keys from test_dict based on the target type targ_type. The filter() function takes two arguments:
  5. A lambda function that checks whether the value of each key is of the target type targ_type.
  6. The keys of test_dict to filter.
  7. The list() function is used to convert the filter object returned by filter() into a list of keys.
  8. Print the extracted keys using the print() function and concatenating the string with str(res).

Python3




# initializing dictionary
test_dict = {'gfg': 2, 'is': 'hello', 'best': 2, 'for': {'1': 3}, 'neveropen': 4}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# initializing type
targ_type = int
 
# using filter() to extract keys
res = list(filter(lambda x: isinstance(
    test_dict[x], targ_type), test_dict.keys()))
 
# printing result
print("The extracted keys : " + str(res))


Output

The original dictionary is : {'gfg': 2, 'is': 'hello', 'best': 2, 'for': {'1': 3}, 'neveropen': 4}
The extracted keys : ['gfg', 'best', 'neveropen']

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():

  1. Import the reduce() method from the functools module.
  2. Define a dictionary test_dict.
  3. 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.
  4. 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.
  5. Pass the keys of the dictionary as the second argument to reduce().
  6. Start with an initial value of an empty list [] for the accumulator.
  7. Store the result of reduce() in the variable res.
  8. 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}, 'neveropen': 4}
 
# using reduce() to extract the keys
# with integer values
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}, 'neveropen': 4}
The extracted keys : ['gfg', 'best', 'neveropen']

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.

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments