Python dictionary length – Everything you need to know

This Python tutorial will discuss how to use and find Python dictionary length.

There are 5 ways to find the length of a dictionary in Python, which is shown below:

  • Using the len() function
  • Using the len() function with keys() method
  • Using the len() function with values() method
  • Using recursion
  • Using the dictionary comprehension

How to find Python dictionary length

Here we will discuss 5 different methods to find the length of a dictionary in Python. And we will start with the basic method of using len() function.

Method-1: Using the len() function

This method is the most straightforward way to find the length of a dictionary in Python. The built-in len() function can be used to return the number of key-value pairs in the dictionary. It works by taking the dictionary as an argument and returning its length.

# Create a dictionary called "my_dict" with three key-value pairs
my_dict = {"Micheal":20,"george":30,"james":40}

# Print the length of the dictionary to the console
print("Length of dictionary:",len(my_dict))

The above code creates a dictionary called my_dict that contains three key-value pairs where each key is a name and each value is an age.

  • It then prints the length of the dictionary to the console using the len() function.
Python dictionary length
Python dictionary length

Read: Python Dictionary sort

Method-2: Using the len() function with keys() method

This method is a variation of the first method, but instead of passing the entire dictionary to the len() function, we use the keys() method of the dictionary to get a list of all the keys and then pass it to the len() function. This returns the number of keys in the dictionary, which is equal to the number of key-value pairs.

# Create a dictionary called "my_dict" with three key-value pairs
my_dict = {'a': 1, 'b': 2, 'c': 3}

# Get the keys of the dictionary using the keys() method, get its length using len(), and print it to the console
print(len(my_dict.keys()))

The above code creates a dictionary called my_dict that contains three key-value pairs. It then uses the keys() method to get a list-like object containing the keys of the dictionary, and then prints the length of that object to the console using the len() function.

Output: 3

Read: Python Dictionary index

Method-3: Using the len() function with values() method

This method is similar to Method 2, but instead of using the keys() method, we use the values() method of the dictionary to get a list of all the values and then pass it to the len() function. This returns the number of values in the dictionary, which is again equal to the number of key-value pairs.

# Create a dictionary called "my_dict" with three key-value pairs
my_dict = {'a': 1, 'b': 2, 'c': 3}

# Get the keys of the dictionary using the values() method, get its length using len(), and print it to the console
print(len(my_dict.values()))

The code creates a dictionary called my_dict with three key-value pairs.

  • It then tries to get the length of the dictionary values by using the values() method and prints the length to the console.
Output: 3

Read: Python Dictionary Count

Method-4 Using recursion

To find the length of a dictionary using recursion, we can define a function that recursively counts the number of key-value pairs in the dictionary.

# Define a recursive function that takes a dictionary as input and counts the total number of key-value pairs
def count_dict(d):
    count = 0
    # Iterate through each key-value pair in the dictionary
    for k, v in d.items():
        count += 1  # Increment the count by 1 for each key-value pair
        # If the value is itself a dictionary, recursively call the function to count its key-value pairs
        if isinstance(v, dict):
            count += count_dict(v)
    # Return the total count of key-value pairs in the dictionary
    return count

# Create a dictionary called "my_dict"
my_dict = {'USA': 1, 'United Kingdom': 2, 'Brazil': 3, 'Canada': 4}

# Call the count_dict function with my_dict as the input and print the total count to the console
print(count_dict(my_dict))

The above code defines a function called count_dict that takes a dictionary as input and recursively counts the number of keys in the dictionary.

  • The function iterates over the key-value pairs of the input dictionary, increments the counter for each key, and recursively calls itself if the value of a key is also a dictionary.
  • The code then creates a dictionary my_dict and calls the count_dict function on it. Finally, the code prints the length of the my_dict dictionary
Output: 4

Read: Python dictionary initialize

Method-5: Using the dictionary comprehension

This method calculates the length of a dictionary using a dictionary comprehension and len() function. The dictionary comprehension converts each key-value pair of the dictionary to a new key-value pair and then calculates the length of the resulting dictionary.


# Define a dictionary called my_dict with key-value pairs
my_dict = {'a': 1, 'b': 2, 'c': 3}

# Create a new dictionary using a dictionary comprehension
# Get the length of the new dictionary
dict_len = len({i: j for i, j in my_dict.items()})

# Print the length of the original dictionary to the console
print("The length of the my_dict dictionary is", dict_len)

The above code creates a dictionary named my_dict with three key-value pairs.

  • It then creates a new dictionary using a dictionary comprehension that has the same key-value pairs as my_dict. It then uses the len() function to get the length of the new dictionary, which is the same as the length of my_dict. Finally, it prints the length of my_dict to the console.
Output: The length of the my_dict dictionary is 3

You may also like to read the following Python tutorials.

Conclusion

In this Python tutorial, we have covered Python dictionary length using the different methods:

  • Using the len() function
  • Using the len() function with keys() method
  • Using the len() function with values() method
  • Using recursion
  • Using the dictionary comprehension