How to Check If a Dictionary Has a Certain Number of Keys in Python

PythonPythonBeginner
Practice Now

Introduction

In this lab, you will learn how to check if a Python dictionary has a specific number of keys. This involves exploring dictionary size using the built-in len() function to determine the number of key-value pairs.

You'll create a Python script to define a dictionary, use len() to get its size, and print the result. You'll also experiment with an empty dictionary to observe the output. This hands-on experience will demonstrate how to effectively use len() to verify the key count in dictionaries.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("Python")) -.-> python/ControlFlowGroup(["Control Flow"]) python(("Python")) -.-> python/DataStructuresGroup(["Data Structures"]) python(("Python")) -.-> python/FunctionsGroup(["Functions"]) python/ControlFlowGroup -.-> python/conditional_statements("Conditional Statements") python/DataStructuresGroup -.-> python/dictionaries("Dictionaries") python/FunctionsGroup -.-> python/build_in_functions("Build-in Functions") subgraph Lab Skills python/conditional_statements -.-> lab-559506{{"How to Check If a Dictionary Has a Certain Number of Keys in Python"}} python/dictionaries -.-> lab-559506{{"How to Check If a Dictionary Has a Certain Number of Keys in Python"}} python/build_in_functions -.-> lab-559506{{"How to Check If a Dictionary Has a Certain Number of Keys in Python"}} end

Explore Dictionary Size

In this step, you will learn how to determine the size of a dictionary in Python. The size of a dictionary refers to the number of key-value pairs it contains. Knowing the size of a dictionary can be useful for various tasks, such as checking if a dictionary is empty or determining if it has reached a certain capacity.

To find the size of a dictionary, you can use the built-in len() function. This function returns the number of items (key-value pairs) in the dictionary.

Let's start by creating a simple Python script to explore this.

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

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

    touch ~/project/dictionary_size.py
  3. Open the dictionary_size.py file in the editor and add the following Python code:

    ## Create a sample dictionary
    my_dict = {
        "name": "Alice",
        "age": 30,
        "city": "New York"
    }
    
    ## Get the size of the dictionary using the len() function
    dict_size = len(my_dict)
    
    ## Print the size of the dictionary
    print("The size of the dictionary is:", dict_size)

    This code first creates a dictionary called my_dict with three key-value pairs. Then, it uses the len() function to get the size of the dictionary and stores it in the dict_size variable. Finally, it prints the size of the dictionary to the console.

  4. Now, run the Python script using the following command in the terminal:

    python ~/project/dictionary_size.py

    You should see the following output:

    The size of the dictionary is: 3

    This output confirms that the len() function correctly returns the number of key-value pairs in the dictionary.

  5. Let's try with an empty dictionary. Modify the dictionary_size.py file to the following:

    ## Create an empty dictionary
    my_dict = {}
    
    ## Get the size of the dictionary using the len() function
    dict_size = len(my_dict)
    
    ## Print the size of the dictionary
    print("The size of the dictionary is:", dict_size)
  6. Run the script again:

    python ~/project/dictionary_size.py

    You should see the following output:

    The size of the dictionary is: 0

    This shows that an empty dictionary has a size of 0.

Use len() on Keys

In the previous step, you learned how to use the len() function to determine the total number of key-value pairs in a dictionary. In this step, you'll explore how to use len() in conjunction with the .keys() method to find the number of keys in a dictionary.

The .keys() method returns a view object that displays a list of all the keys in the dictionary. You can then use the len() function on this view object to get the count of keys. This can be useful when you only need to know the number of keys and not the total number of key-value pairs.

Let's modify the Python script from the previous step to demonstrate this.

  1. Open the dictionary_size.py file in the VS Code editor (if it's not already open).

  2. Modify the dictionary_size.py file to the following Python code:

    ## Create a sample dictionary
    my_dict = {
        "name": "Alice",
        "age": 30,
        "city": "New York"
    }
    
    ## Get the keys of the dictionary using the .keys() method
    keys = my_dict.keys()
    
    ## Get the number of keys using the len() function
    num_keys = len(keys)
    
    ## Print the number of keys
    print("The number of keys in the dictionary is:", num_keys)

    In this code, we first create a dictionary called my_dict. Then, we use the .keys() method to get a view object containing all the keys in the dictionary. We store this view object in the keys variable. Finally, we use the len() function to get the number of keys in the keys view object and print the result.

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

    python ~/project/dictionary_size.py

    You should see the following output:

    The number of keys in the dictionary is: 3

    This output confirms that the len() function, when used with the .keys() method, correctly returns the number of keys in the dictionary.

  4. Now, let's try adding a new key-value pair to the dictionary and see how it affects the number of keys. Modify the dictionary_size.py file to the following:

    ## Create a sample dictionary
    my_dict = {
        "name": "Alice",
        "age": 30,
        "city": "New York"
    }
    
    ## Add a new key-value pair
    my_dict["occupation"] = "Engineer"
    
    ## Get the keys of the dictionary using the .keys() method
    keys = my_dict.keys()
    
    ## Get the number of keys using the len() function
    num_keys = len(keys)
    
    ## Print the number of keys
    print("The number of keys in the dictionary is:", num_keys)
  5. Run the script again:

    python ~/project/dictionary_size.py

    You should see the following output:

    The number of keys in the dictionary is: 4

    This shows that adding a new key-value pair increases the number of keys in the dictionary.

Compare with Desired Count

In the previous steps, you learned how to determine the size of a dictionary and how to count the number of keys. In this step, you'll learn how to compare the size of a dictionary (or the number of keys) with a desired count. This is useful when you need to validate that a dictionary has a specific number of key-value pairs or keys before proceeding with further operations.

Let's modify the Python script from the previous step to demonstrate this.

  1. Open the dictionary_size.py file in the VS Code editor (if it's not already open).

  2. Modify the dictionary_size.py file to the following Python code:

    ## Create a sample dictionary
    my_dict = {
        "name": "Alice",
        "age": 30,
        "city": "New York"
    }
    
    ## Desired count
    desired_count = 3
    
    ## Get the size of the dictionary
    dict_size = len(my_dict)
    
    ## Compare with desired count
    if dict_size == desired_count:
        print("The dictionary size matches the desired count.")
    else:
        print("The dictionary size does not match the desired count.")
    
    ## Get the number of keys
    num_keys = len(my_dict.keys())
    
    ## Compare the number of keys with desired count
    if num_keys == desired_count:
        print("The number of keys matches the desired count.")
    else:
        print("The number of keys does not match the desired count.")

    In this code, we first create a dictionary called my_dict and set a desired_count variable to 3. Then, we get the size of the dictionary using the len() function and compare it with the desired_count. We print a message indicating whether the dictionary size matches the desired count. We then repeat the same process for the number of keys in the dictionary.

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

    python ~/project/dictionary_size.py

    You should see the following output:

    The dictionary size matches the desired count.
    The number of keys matches the desired count.

    This output confirms that the dictionary size and the number of keys both match the desired count of 3.

  4. Now, let's modify the dictionary and the desired count to see how the comparison changes. Modify the dictionary_size.py file to the following:

    ## Create a sample dictionary
    my_dict = {
        "name": "Alice",
        "age": 30,
        "city": "New York"
    }
    
    ## Add a new key-value pair
    my_dict["occupation"] = "Engineer"
    
    ## Desired count
    desired_count = 4
    
    ## Get the size of the dictionary
    dict_size = len(my_dict)
    
    ## Compare with desired count
    if dict_size == desired_count:
        print("The dictionary size matches the desired count.")
    else:
        print("The dictionary size does not match the desired count.")
    
    ## Get the number of keys
    num_keys = len(my_dict.keys())
    
    ## Compare the number of keys with desired count
    if num_keys == desired_count:
        print("The number of keys matches the desired count.")
    else:
        print("The number of keys does not match the desired count.")
  5. Run the script again:

    python ~/project/dictionary_size.py

    You should see the following output:

    The dictionary size matches the desired count.
    The number of keys matches the desired count.

    Now, both the dictionary size and the number of keys match the updated desired count of 4.

Summary

In this lab, you learned how to determine the size of a Python dictionary using the len() function. The lab involved creating a Python script, dictionary_size.py, to explore this functionality. You created a sample dictionary with key-value pairs and then used len(my_dict) to obtain the number of items in the dictionary, printing the result to the console.

The lab also demonstrated how the len() function works with an empty dictionary, highlighting its ability to accurately return the number of key-value pairs, even when the dictionary is empty. This knowledge is crucial for tasks like checking if a dictionary is empty or determining if it has reached a specific capacity.