How to Check If a Variable Is a Dictionary in Python

PythonPythonBeginner
Practice Now

Introduction

In this lab, you will learn how to check if a variable is a dictionary in Python. Dictionaries are fundamental data structures used to store data in key-value pairs. You'll start by understanding the basics of dictionaries, including how to create, access, and modify them using curly braces {} and key-based indexing.

The lab then guides you through using the type() function and the isinstance() function to identify whether a variable is a dictionary. You'll create Python scripts to test these methods and observe the output, solidifying your understanding of how to programmatically determine if a variable holds a dictionary object.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("Python")) -.-> python/BasicConceptsGroup(["Basic Concepts"]) python(("Python")) -.-> python/DataStructuresGroup(["Data Structures"]) python(("Python")) -.-> python/FunctionsGroup(["Functions"]) python(("Python")) -.-> python/PythonStandardLibraryGroup(["Python Standard Library"]) python/BasicConceptsGroup -.-> python/variables_data_types("Variables and Data Types") python/BasicConceptsGroup -.-> python/booleans("Booleans") python/DataStructuresGroup -.-> python/dictionaries("Dictionaries") python/FunctionsGroup -.-> python/build_in_functions("Build-in Functions") python/PythonStandardLibraryGroup -.-> python/data_collections("Data Collections") subgraph Lab Skills python/variables_data_types -.-> lab-559599{{"How to Check If a Variable Is a Dictionary in Python"}} python/booleans -.-> lab-559599{{"How to Check If a Variable Is a Dictionary in Python"}} python/dictionaries -.-> lab-559599{{"How to Check If a Variable Is a Dictionary in Python"}} python/build_in_functions -.-> lab-559599{{"How to Check If a Variable Is a Dictionary in Python"}} python/data_collections -.-> lab-559599{{"How to Check If a Variable Is a Dictionary in Python"}} end

Understand Dictionaries

In this step, you will learn about dictionaries, a fundamental data structure in Python. Dictionaries are used to store data in key-value pairs, allowing you to quickly retrieve values based on their associated keys.

A dictionary is defined using curly braces {}. Each key-value pair is separated by a colon :, and pairs are separated by commas ,. Here's a simple example:

my_dict = {"name": "Alice", "age": 30, "city": "New York"}
print(my_dict)

To work with dictionaries, let's create a Python file named dictionary_example.py in your ~/project directory using the VS Code editor.

Open VS Code, create a new file named dictionary_example.py in the ~/project directory, and add the following content:

## Create a dictionary
my_dict = {"name": "Alice", "age": 30, "city": "New York"}

## Print the entire dictionary
print(my_dict)

Now, execute the Python script using the following command in the terminal:

python ~/project/dictionary_example.py

You should see the following output:

{'name': 'Alice', 'age': 30, 'city': 'New York'}

To access a specific value in the dictionary, use the key within square brackets []:

name = my_dict["name"]
print(name)

Modify your dictionary_example.py file to include the following lines:

## Create a dictionary
my_dict = {"name": "Alice", "age": 30, "city": "New York"}

## Access a value using the key
name = my_dict["name"]
print(name)

Execute the script again:

python ~/project/dictionary_example.py

The output will now be:

Alice

You can also add new key-value pairs to a dictionary:

my_dict["occupation"] = "Engineer"
print(my_dict)

Update your dictionary_example.py file:

## Create a dictionary
my_dict = {"name": "Alice", "age": 30, "city": "New York"}

## Add a new key-value pair
my_dict["occupation"] = "Engineer"
print(my_dict)

Run the script:

python ~/project/dictionary_example.py

The output will be:

{'name': 'Alice', 'age': 30, 'city': 'New York', 'occupation': 'Engineer'}

Dictionaries are mutable, meaning you can change the value associated with a key:

my_dict["age"] = 31
print(my_dict)

Modify your dictionary_example.py file:

## Create a dictionary
my_dict = {"name": "Alice", "age": 30, "city": "New York"}

## Change the value of an existing key
my_dict["age"] = 31
print(my_dict)

Execute the script:

python ~/project/dictionary_example.py

The output will be:

{'name': 'Alice', 'age': 31, 'city': 'New York'}

Understanding dictionaries is crucial for working with structured data in Python. They provide a flexible and efficient way to store and retrieve information.

Use type() to Identify

In this step, you will learn how to use the type() function in Python to identify the data type of a variable. This is a useful tool for understanding the kind of data you are working with and for debugging your code.

The type() function returns the type of an object. For example, if you have a variable containing an integer, type() will return <class 'int'>. If it contains a string, it will return <class 'str'>, and so on.

Let's continue working with the dictionary_example.py file you created in the previous step. We'll add some code to identify the types of different variables.

Open dictionary_example.py in VS Code and add the following lines:

## Create a dictionary
my_dict = {"name": "Alice", "age": 30, "city": "New York"}

## Check the type of the dictionary
print(type(my_dict))

## Access a value
name = my_dict["name"]

## Check the type of the value
print(type(name))

## Check the type of the age
age = my_dict["age"]
print(type(age))

Now, execute the Python script using the following command:

python ~/project/dictionary_example.py

You should see the following output:

<class 'dict'>
<class 'str'>
<class 'int'>

This output tells you that my_dict is a dictionary (dict), name is a string (str), and age is an integer (int).

You can also use type() with other data types, such as lists and booleans. Let's add some more examples to dictionary_example.py:

## Create a dictionary
my_dict = {"name": "Alice", "age": 30, "city": "New York"}

## Check the type of the dictionary
print(type(my_dict))

## Access a value
name = my_dict["name"]

## Check the type of the value
print(type(name))

## Check the type of the age
age = my_dict["age"]
print(type(age))

## Create a list
my_list = [1, 2, 3]
print(type(my_list))

## Create a boolean
is_adult = True
print(type(is_adult))

Execute the script again:

python ~/project/dictionary_example.py

The output will now be:

<class 'dict'>
<class 'str'>
<class 'int'>
<class 'list'>
<class 'bool'>

As you can see, type() is a versatile function that can help you understand the data types you are working with in Python. This is especially useful when you are dealing with complex data structures or when you are unsure of the type of a variable.

Confirm with isinstance()

In this step, you will learn how to use the isinstance() function in Python to confirm if an object is an instance of a particular class or type. This function is more robust than type() because it also considers inheritance.

The isinstance() function takes two arguments: the object you want to check and the class or type you want to check against. It returns True if the object is an instance of the specified class or type, and False otherwise.

Let's continue working with the dictionary_example.py file. We'll add some code to confirm the types of different variables using isinstance().

Open dictionary_example.py in VS Code and add the following lines:

## Create a dictionary
my_dict = {"name": "Alice", "age": 30, "city": "New York"}

## Check if my_dict is a dictionary
print(isinstance(my_dict, dict))

## Access a value
name = my_dict["name"]

## Check if name is a string
print(isinstance(name, str))

## Check if age is an integer
age = my_dict["age"]
print(isinstance(age, int))

Now, execute the Python script using the following command:

python ~/project/dictionary_example.py

You should see the following output:

True
True
True

This output confirms that my_dict is a dictionary, name is a string, and age is an integer.

You can also use isinstance() to check against multiple types at once by passing a tuple of types as the second argument. For example:

## Check if age is either an integer or a float
print(isinstance(age, (int, float)))

Modify your dictionary_example.py file to include this check:

## Create a dictionary
my_dict = {"name": "Alice", "age": 30, "city": "New York"}

## Check if my_dict is a dictionary
print(isinstance(my_dict, dict))

## Access a value
name = my_dict["name"]

## Check if name is a string
print(isinstance(name, str))

## Check if age is an integer
age = my_dict["age"]
print(isinstance(age, int))

## Check if age is either an integer or a float
print(isinstance(age, (int, float)))

Execute the script again:

python ~/project/dictionary_example.py

The output will now be:

True
True
True
True

isinstance() is a powerful tool for type checking in Python, especially when dealing with inheritance or when you need to check against multiple types. It helps you write more robust and reliable code by ensuring that your variables are of the expected types.

Summary

In this lab, you learned about dictionaries in Python, a fundamental data structure for storing data in key-value pairs. You created a dictionary, accessed values using keys, and added new key-value pairs.

You also practiced using the type() function and the isinstance() function to verify if a variable is a dictionary. The type() function returns the type of an object, while isinstance() checks if an object is an instance of a specified class or type.