Python Program to Extract Keys with specific Value Type


Python's implementation of a data structure known more commonly as an associative array is a dictionary. A dictionary is made up of a group of key-value pairs. Each key-value combination corresponds to a key and its corresponding value.

In this article, we will learn how to extract keys with specific value type in python.

Methods Used

The following are the various methods to accomplish this task −

  • Using for loop and isinstance() method

  • Using list comprehension and isinstance() method

  • Using keys() & type() methods

Example

Assume we have taken an input dictionary. We will now

Input

inputDict = {'hello': 5, 'tutorials': 'hi', 'users': 2, 'codes': 'user', 'python': [1, 2]}
extractType = str

Output

['tutorials', 'codes']

In the above input dictionary, the values having str(string) type are 'hi' and 'user'. The corresponding keys of those values are 'tutorials' and 'codes' respectively. Hence these keys are extracted.

Using for loop and isinstance() method

isinstance() function

If the given object is of the specified type, the isinstance() function returns True; else, it returns False.

It returns True if the object is one of the types in the tuple if the type parameter is a tuple.

Syntax

isinstance(object, type)

Parameters

  • object − an object that has to be checked to see if it belongs to the class.

  • type − A type or a class, or a tuple of types and/or classes

Algorithm (Steps)

Following are the Algorithm/steps to be followed to perform the desired task –.

  • Create a variable to store an input dictionary having multiple datatypes.

  • Print the input dictionary.

  • Create another variable to store the input datatype to be extracted.

  • Initialize an empty list to store the resultant keys of specified input type.

  • Use the for loop to traverse through keys, and values of the input dictionary using the items() function.

  • Use the if conditional statement to check whether the current value type is equal to the input extract type using isinstance() function.

  • Use the append() function(adds the element to the list at the end) to append that corresponding key to the resultant keys list if the condition is true.

  • Print the resultant keys of an input dictionary having the specified input type.

Example

The following program returns keys of the given input value type from an input dictionary using the for loop and isinstance() method –

# input dictionary having multiple datatypes
inputDict = {'hello': 5, 'tutorials': 'hi',
   'users': 2, 'codes': 'user', 'python': [1, 2]}
# printing input dictionary
print("Input dictionary:\n", inputDict)
# input datatype to be extracted
extractType = str
# storing resultant keys of input type
resultantKeys = []
# traversing through keys, values of input dictionary
for k, v in inputDict.items():
    # checking whether the current value type is equal to the input data type
    if isinstance(v, extractType):
        # appending that corresponding key to the resultant keys list
        resultantKeys.append(k)
# printing the resultant keys of the dictionary having the specified input type
print("Resultant keys of input dictionary with 'string' type:\n", resultantKeys)

Output

On executing, the above program will generate the following output –

Input dictionary:
 {'hello': 5, 'tutorials': 'hi', 'users': 2, 'codes': 'user', 'python': [1, 2]}
Resultant keys of input dictionary with 'string' type:
 ['tutorials', 'codes']

Using list comprehension and isinstance() method

When you wish to build a new list based on the values of an existing list, list comprehension provides a shorter/concise syntax.

Example

The following program returns keys of the given input value type from an input dictionary using the list comprehension and isinstance() method –

# input dictionary having multiple datatypes 
inputDict = {'hello': 5, 'tutorials': 'hi', 'users': 2, 'codes': 'user', 'python': [1, 2]}
# printing input dictionary
print("Input dictionary:\n", inputDict)
# input datatype to be extracted 
extractType = str
# Using list comprehension to extract keys with string datatype
resultantKeys = [k for k, v in inputDict.items() if isinstance(v, extractType)]
# printing the resultant keys of the dictionary having the specified input type
print("Resultant keys of input dictionary with 'string' type:\n", resultantKeys)

Output

On executing, the above program will generate the following output –

Input dictionary:
 {'hello': 5, 'tutorials': 'hi', 'users': 2, 'codes': 'user', 'python': [1, 2]}
Resultant keys of input dictionary with 'string' type:
 ['tutorials', 'codes']

Method 3 Using keys() & type() methods

keys() method − dict. keys() method provides a view object that displays a list of all the keys in the dictionary in order of insertion).

type() function(returns the data type of an object).

Algorithm (Steps)

Following are the Algorithm/steps to be followed to perform the desired task –.

  • Use the for loop to traverse through the keys of an input dictionary using keys() function

  • Use the if conditional statement to check whether the type of current value is equal to the input extract type using type() function.

  • Use the append() function(adds the element to the list at the end) to append the current key to the resultant keys list if the condition is true.

  • Print the resultant keys of an input dictionary having the specified input type.

Example

The following program returns keys of the given input value type from an input dictionary using the keys() & type() functions –

# input dictionary having multiple datatypes
inputDict = {'hello': 5, 'tutorials': 'hi', 'users': 2, 'codes': 'user', 'python': [1, 2]}
# printing input dictionary
print("Input dictionary:\n", inputDict)
# input datatype to be extracted
extractType = str
# storing resultant keys of input type
resultantKeys = []
# traversing through keys of input dictionary
for k in inputDict.keys():
  # checking whether the current value type of that corresponding key
  # is equal to the input extract type
    if type(inputDict[k]) is extractType:
        # appending the current key to the resultant list 
        resultantKeys.append(k)
# printing the resultant keys of the dictionary having the specified input type
print("Resultant keys of input dictionary with 'string' type:\n", resultantKeys)

Output

On executing, the above program will generate the following output –

Input dictionary:
 {'hello': 5, 'tutorials': 'hi', 'users': 2, 'codes': 'user', 'python': [1, 2]}
Resultant keys of input dictionary with 'string' type:
 ['tutorials', 'codes']

Conclusion

This article has taught us three different ways to extract keys with specific value types. Additionally, we learned how to use the type() function to determine a variable's type and the isinstance() method to compare two data types.

Updated on: 18-Aug-2023

67 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements