How to Check If a Dictionary Is Empty in Python

PythonPythonBeginner
Practice Now

Introduction

In this lab, you will learn how to determine if a dictionary is empty in Python. The lab covers creating empty dictionaries using curly braces {} and the dict() constructor. You'll then explore how to use the len() function to check the number of key-value pairs in a dictionary, effectively identifying empty dictionaries.

Finally, the lab will demonstrate how empty dictionaries are evaluated in boolean contexts, providing a comprehensive understanding of working with and identifying empty dictionaries in Python.


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/ObjectOrientedProgrammingGroup(["Object-Oriented Programming"]) python/BasicConceptsGroup -.-> python/booleans("Booleans") python/DataStructuresGroup -.-> python/dictionaries("Dictionaries") python/FunctionsGroup -.-> python/build_in_functions("Build-in Functions") python/ObjectOrientedProgrammingGroup -.-> python/constructor("Constructor") subgraph Lab Skills python/booleans -.-> lab-559507{{"How to Check If a Dictionary Is Empty in Python"}} python/dictionaries -.-> lab-559507{{"How to Check If a Dictionary Is Empty in Python"}} python/build_in_functions -.-> lab-559507{{"How to Check If a Dictionary Is Empty in Python"}} python/constructor -.-> lab-559507{{"How to Check If a Dictionary Is Empty in Python"}} end

Learn About Empty Dictionaries

In this step, you will learn about empty dictionaries in Python. A dictionary is a collection of key-value pairs, and an empty dictionary is simply a dictionary that contains no key-value pairs. Understanding how to create and work with empty dictionaries is fundamental to many programming tasks.

To create an empty dictionary, you can use either curly braces {} or the dict() constructor. Let's see how to do this in practice.

  1. Open the VS Code editor in the LabEx environment.

  2. Create a new file named empty_dict.py in the ~/project directory.

    ~/project/empty_dict.py
  3. Add the following Python code to the empty_dict.py file:

    ## Creating an empty dictionary using curly braces
    empty_dict_1 = {}
    print("Empty dictionary 1:", empty_dict_1)
    
    ## Creating an empty dictionary using the dict() constructor
    empty_dict_2 = dict()
    print("Empty dictionary 2:", empty_dict_2)

    This code creates two empty dictionaries, empty_dict_1 and empty_dict_2, using different methods. The print() function is then used to display these dictionaries.

  4. Run the Python script using the following command in the terminal:

    python ~/project/empty_dict.py

    You should see the following output:

    Empty dictionary 1: {}
    Empty dictionary 2: {}

    This output confirms that both methods successfully created empty dictionaries.

Empty dictionaries are useful as starting points for building more complex data structures. You can add key-value pairs to them as needed. In the next steps, you'll learn how to check if a dictionary is empty and how empty dictionaries are evaluated in boolean contexts.

Use len() to Check

In this step, you will learn how to use the len() function to check if a dictionary is empty. The len() function returns the number of items (key-value pairs) in a dictionary. If a dictionary is empty, len() will return 0.

Let's modify the empty_dict.py file you created in the previous step to include the len() function.

  1. Open the empty_dict.py file in the VS Code editor.

    ~/project/empty_dict.py
  2. Modify the Python code in the empty_dict.py file to include the len() function:

    ## Creating an empty dictionary using curly braces
    empty_dict_1 = {}
    print("Empty dictionary 1:", empty_dict_1)
    print("Length of empty_dict_1:", len(empty_dict_1))
    
    ## Creating an empty dictionary using the dict() constructor
    empty_dict_2 = dict()
    print("Empty dictionary 2:", empty_dict_2)
    print("Length of empty_dict_2:", len(empty_dict_2))
    
    ## Checking if a dictionary is empty using len()
    if len(empty_dict_1) == 0:
        print("empty_dict_1 is empty")
    else:
        print("empty_dict_1 is not empty")

    This code calculates the length of the empty dictionaries using len() and prints the result. It also demonstrates how to use len() in a conditional statement to check if a dictionary is empty.

  3. Run the Python script using the following command in the terminal:

    python ~/project/empty_dict.py

    You should see the following output:

    Empty dictionary 1: {}
    Length of empty_dict_1: 0
    Empty dictionary 2: {}
    Length of empty_dict_2: 0
    empty_dict_1 is empty

    This output confirms that the len() function returns 0 for empty dictionaries, and the conditional statement correctly identifies the dictionary as empty.

Using len() is a simple and effective way to determine if a dictionary contains any key-value pairs. This can be useful in various scenarios, such as when you need to perform different actions based on whether a dictionary is empty or not.

Evaluate as Boolean

In this step, you will learn how empty dictionaries are evaluated in a boolean context. In Python, certain values are considered "truthy" (evaluate to True) and others are considered "falsy" (evaluate to False) when used in a boolean context, such as in an if statement. An empty dictionary is considered "falsy".

Let's modify the empty_dict.py file you've been working with to demonstrate this concept.

  1. Open the empty_dict.py file in the VS Code editor.

    ~/project/empty_dict.py
  2. Modify the Python code in the empty_dict.py file to include a boolean evaluation of an empty dictionary:

    ## Creating an empty dictionary using curly braces
    empty_dict_1 = {}
    print("Empty dictionary 1:", empty_dict_1)
    print("Length of empty_dict_1:", len(empty_dict_1))
    
    ## Creating an empty dictionary using the dict() constructor
    empty_dict_2 = dict()
    print("Empty dictionary 2:", empty_dict_2)
    print("Length of empty_dict_2:", len(empty_dict_2))
    
    ## Checking if a dictionary is empty using len()
    if len(empty_dict_1) == 0:
        print("empty_dict_1 is empty")
    else:
        print("empty_dict_1 is not empty")
    
    ## Evaluating an empty dictionary as a boolean
    if empty_dict_1:
        print("empty_dict_1 is truthy")
    else:
        print("empty_dict_1 is falsy")

    This code adds an if statement that directly evaluates the empty_dict_1 variable. Because it's an empty dictionary, it will be treated as False in the boolean context.

  3. Run the Python script using the following command in the terminal:

    python ~/project/empty_dict.py

    You should see the following output:

    Empty dictionary 1: {}
    Length of empty_dict_1: 0
    Empty dictionary 2: {}
    Length of empty_dict_2: 0
    empty_dict_1 is empty
    empty_dict_1 is falsy

    This output confirms that the empty dictionary empty_dict_1 is evaluated as "falsy" in the if statement.

Understanding that empty dictionaries evaluate to False can simplify your code and make it more readable. You can directly use a dictionary in a boolean context without explicitly checking its length.

Summary

In this lab, you learned about empty dictionaries in Python and how to create them using either curly braces {} or the dict() constructor. You created a empty_dict.py file and used the print() function to display the created empty dictionaries, confirming that both methods successfully created empty dictionaries.

The lab also introduced the concept of using the len() function to check if a dictionary is empty, which will be further explored in subsequent steps.