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