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.
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.
Open the VS Code editor in the LabEx environment.
Create a new file named
dictionary_size.pyin the~/projectdirectory.touch ~/project/dictionary_size.pyOpen the
dictionary_size.pyfile 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_dictwith three key-value pairs. Then, it uses thelen()function to get the size of the dictionary and stores it in thedict_sizevariable. Finally, it prints the size of the dictionary to the console.Now, run the Python script using the following command in the terminal:
python ~/project/dictionary_size.pyYou should see the following output:
The size of the dictionary is: 3This output confirms that the
len()function correctly returns the number of key-value pairs in the dictionary.Let's try with an empty dictionary. Modify the
dictionary_size.pyfile 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)Run the script again:
python ~/project/dictionary_size.pyYou should see the following output:
The size of the dictionary is: 0This 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.
Open the
dictionary_size.pyfile in the VS Code editor (if it's not already open).Modify the
dictionary_size.pyfile 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 thekeysvariable. Finally, we use thelen()function to get the number of keys in thekeysview object and print the result.Run the Python script using the following command in the terminal:
python ~/project/dictionary_size.pyYou should see the following output:
The number of keys in the dictionary is: 3This output confirms that the
len()function, when used with the.keys()method, correctly returns the number of keys in the dictionary.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.pyfile 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)Run the script again:
python ~/project/dictionary_size.pyYou should see the following output:
The number of keys in the dictionary is: 4This 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.
Open the
dictionary_size.pyfile in the VS Code editor (if it's not already open).Modify the
dictionary_size.pyfile 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_dictand set adesired_countvariable to 3. Then, we get the size of the dictionary using thelen()function and compare it with thedesired_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.Run the Python script using the following command in the terminal:
python ~/project/dictionary_size.pyYou 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.
Now, let's modify the dictionary and the desired count to see how the comparison changes. Modify the
dictionary_size.pyfile 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.")Run the script again:
python ~/project/dictionary_size.pyYou 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.



