Python: Check if Variable is a Dictionary

Introduction

Variables act as a container to store data. A developer can use type hints when creating variables or passing arguments, however, that's an optional feature in Python, and many codebases, old and new, are yet to have them. It's more common for a variable in Python to have no information of the type being stored.

If we had code that needed a dictionary but lacked type hints, how can we avoid errors if the variable used is not a dictionary?

In this tutorial, we'll take a look at how to check if a variable is a dictionary in Python, using the type() and isinstance() functions, as well as the is operator:

Developers usually use type() and is, though, these can be limited in certain contexts, in which case, it's better to use the isinstance() function.

Check if Variable is a Dictionary with type()

We can use the type() function to instantly get the type of any variable. For a variable of type Dictionary, it must return <class 'dict'>:

squares = {1: 1, 2: 4, 3: 9}
print(type(squares))

This results in:

<class 'dict'>

Check if Variable is a Dictionary with is Operator

In Python, is is an identity operator. It verifies if both the operands are identical to each other. Being identical indicates that they refer to the same memory location.

We can use the is operator with the result of a type() call with a variable and the dict class. It will output True only if the type() points to the same memory location as the dict class. Otherwise, it will output False.

As a sanity check, we can use the id() function to get the address of the object in memory and verify the comparison:

squares = {1: 1, 2: 4, 3: 9}
print(type(squares) is dict)  # True
print("memory address of type(squares):", id(type(squares)))
print("memory address of dict:", id(dict))  # Should have same ID as type(squares)

This code will produce the following output on a Python interpreter:

True
memory address of type(squares): 1609576584
memory address of dict: 1609576584

Note: The memory address may vary for you, but the same ID should be present for both the type(squares) and dict.

One caveat of this method is that it fails to work if the variable is a type that's a subclass of dict. For example, the previous code would not work if the squares variable was an Ordered Dictionary instead:

from collections import OrderedDict

squares = OrderedDict([(1, 1), (2, 4), (3, 9)])
print(type(squares) is dict)  # False
print("memory address of type(squares):", id(type(squares)))
print("memory address of dict:", id(dict))  # Different ID as they're different classes

This outputs:

False
memory address of type(squares): 9464512
memory address of dict: 9481952

If your code is required to work on subclasses of Dictionaries, then you would prefer to use the isinstance() method.

Check if Variable is a Dictionary with isinstance()

As we have seen, the is operator will return True when the memory address of both the objects is the same. If we have a Dictionary of type inherited from class dict, it will return False. For example, a Dictionary of a subclass of dict like OrderedDict or defaultdict will not point to the same memory address as of dict.

Here we have the isinstance() function to the rescue. This function takes two arguments; an object and a class. If the object is an instance of the class or its subclasses, it will return True. If the object is not an instance of the given class, whether direct or indirect, it returns False.

Here is a code example to check if the variable is a Dictionary using the isinstance() function:

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

from collections import OrderedDict

# Variable of type dict
squares = {1: 1, 2: 4, 3: 9}
print(isinstance(squares, dict))  # True

# Variable of type OrderedDict (Subclass of dict)
cubes = OrderedDict(((1, 1), (2, 8)))
print(isinstance(cubes, dict))  # True

This code will produce the following output on a Python interpreter:

True
True

Conclusion

This tutorial showed ways in which we can check if a variable is a Dictionary. We have first seen the type() function which outputs <class 'dict'> for any Dictionary object. Then we have seen the use of the is operator to check if the type of variable points to dict in the memory location. This returns True or False accordingly.

Lastly, we have seen that is fails at identifying inherited Dictionary objects. When we want to capture inherited objects, we can use the isinstance() function. It returns True if the object is directly or indirectly an instance of the given class (dict in this article), and False otherwise.

As both these methods return True or False, we can easily use them in conditional statements. Unless you explicitly want to reject subclasses of dict, the isinstance() function is the most reliable way to check if a variable is a Dictionary.

Last Updated: February 27th, 2023
Was this article helpful?

Improve your dev skills!

Get tutorials, guides, and dev jobs in your inbox.

No spam ever. Unsubscribe at any time. Read our Privacy Policy.

Naazneen JatuAuthor

Freelance Python Developer

© 2013-2024 Stack Abuse. All rights reserved.

AboutDisclosurePrivacyTerms