How do I check if a value is a dictionary in Python without using isinstance()?
Gable E
gable e profile pic

To check if a value is a dictionary in Python without using theisinstance() function, you can utilize thetype() function and compare it with thedict type. Additionally, you can also check if the value supports dictionary-like operations by verifying if it has the necessary methods and attributes. Here's an example of how you can perform this check:


def is_dict(value):
    return type(value) is dict or hasattr(value, '__getitem__') and hasattr(value, 'keys')

# Usage:
value1 = {'key': 'value'}
value2 = {}
value3 = 'Not a dictionary'

print(is_dict(value1))  # Output: True
print(is_dict(value2))  # Output: True
print(is_dict(value3))  # Output: False

In the above code, theis_dict() function takes avalue parameter and performs the following checks: -type(value) is dict: This checks if the type of the value is exactly the built-indict type. It returnsTrue if the value is a dictionary object. -hasattr(value, '__getitem__') and hasattr(value, 'keys'): This checks if the value has both the__getitem__ method and thekeys attribute. This verifies if the value supports dictionary-like operations, such as accessing items using square brackets (value[key]) and retrieving keys. By combining these checks using the logical OR operator (or), the function determines if the value is a dictionary. If any of the conditions are true, the function returnsTrue; otherwise, it returnsFalse. You can use theis_dict() function by passing a value as an argument. It will check if the value is a dictionary based on the conditions described above. The result is then printed accordingly. It's important to note that this approach may consider objects with similar behavior to dictionaries, such as custom classes implementing the required methods and attributes, as dictionaries. However, it may not catch all cases, particularly if the value is an instance of a subclass ofdict or an object that closely resembles a dictionary.