Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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 using three different approaches.
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
Problem Example
Let's consider an input dictionary with mixed value types ?
inputDict = {'hello': 5, 'tutorials': 'hi', 'users': 2, 'codes': 'user', 'python': [1, 2]}
extractType = str
print("Input dictionary:", inputDict)
print("Extract type:", extractType.__name__)
Input dictionary: {'hello': 5, 'tutorials': 'hi', 'users': 2, 'codes': 'user', 'python': [1, 2]}
Extract type: str
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 should be extracted.
Using for loop and isinstance() method
The isinstance() function checks if an object belongs to a specific type. It returns True if the object matches the specified type, otherwise False.
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
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]}
# 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:", resultantKeys)
Resultant keys of input dictionary with 'string' type: ['tutorials', 'codes']
Using List Comprehension and isinstance() method
List comprehension provides a concise way to create lists based on existing iterables. We can combine it with isinstance() for a more compact solution ?
# input dictionary having multiple datatypes
inputDict = {'hello': 5, 'tutorials': 'hi', 'users': 2, 'codes': 'user', 'python': [1, 2]}
# 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:", resultantKeys)
Resultant keys of input dictionary with 'string' type: ['tutorials', 'codes']
Using keys() and type() methods
The keys() method returns all dictionary keys, while type() returns the exact type of an object. Unlike isinstance(), type() doesn't consider inheritance ?
# input dictionary having multiple datatypes
inputDict = {'hello': 5, 'tutorials': 'hi', 'users': 2, 'codes': 'user', 'python': [1, 2]}
# 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:", resultantKeys)
Resultant keys of input dictionary with 'string' type: ['tutorials', 'codes']
Comparison of Methods
| Method | Readability | Performance | Inheritance Support |
|---|---|---|---|
| For loop + isinstance() | Good | Standard | Yes |
| List comprehension + isinstance() | Excellent | Fastest | Yes |
| keys() + type() | Good | Standard | No |
Conclusion
Use list comprehension with isinstance() for the most readable and efficient solution. The isinstance() method is preferred over type() as it handles inheritance properly, making your code more robust.
