search

How to check if a variable is a dictionary in Python?

To check if a variable is a dictionary in Python, you can use the isinstance() function or compare the type of the variable to the dict type. Here's an example:

# Using isinstance()
x = {"name": "John", "age": 30}
if isinstance(x, dict):
    print("x is a dictionary")
else:
    print("x is not a dictionary")

# Using type()
y = [1, 2, 3]
if type(y) == dict:
    print("y is a dictionary")
else:
    print("y is not a dictionary")

In the above example, the isinstance() function is used to check if the variable x is an instance of the dict type. If it is, it prints "x is a dictionary"; otherwise, it prints "x is not a dictionary".

Similarly, the type() function is used to compare the type of the variable y with the dict type. If they are equal, it prints "y is a dictionary"; otherwise, it prints "y is not a dictionary".

Keep in mind that both isinstance() and type() checks will only identify variables that are specifically of the dict type. If you want to include other types that behave like dictionaries, such as instances of subclasses of the dict type, you can modify the checks accordingly. For example, you can use isinstance(x, (dict, OrderedDict)) to check if the variable x is either a dictionary or an ordered dictionary.

Related Questions You Might Be Interested