To find the length of a dictionary in Python, the easiest way is to use the Python len() function. The len() function returns the number of key/value pairs in the dictionary and the size of the dictionary.

length_of_dictionary = len(dictionary)

In Python, dictionaries are a collection of key/value pairs separated by commas. When working with dictionaries, it can be useful to be able to easily calculate the length and size of a dictionary.

To get the length of a dictionary in Python, we can use the Python len() function.

Let’s say we have the following dictionary in our Python code.

dictionary = { "key1":"This", "key2":"is", "key3":"a", "key4":"dictionary." }

To get the size of our dictionary variable, we can call the len() function.

dictionary = { "key1":"This", "key2":"is", "key3":"a", "key4":"dictionary." }

length_of_dictionary = len(dictionary)

print(length_of_dictionary)

#Output:
4

As you can see above, there are 4 key/value pairs, and as a result, the len() function returns 4.

Using the Python len() Function to Find the Length of Other Objects in Python

The Python len() function is one of the most used functions in the Python programming language.

You can also use the len() function to find the length of a string, the length of a list, the length of a set, and the length of a tuple in Python.

For example, if I wanted to find the length of the following string variable, I’d just pass it to the len() function.

print(len("This is a string variable."))

#Output:
26

Hopefully this article has been useful for you to learn how to use the Python len() function to find the length of a dictionary.

Categorized in:

Python,

Last Update: March 20, 2024