Python dictionary len() method [With Example]

In this Python tutorial, we will discuss everything about the Python Dictionary len() method. I will also show you, the syntax of len() dictionary method and how to use the dictionary len() method with a few examples.

Python dictionary len() method

In Python, the len() function is used to return the total number of items in an object. When applied to a dictionary, it returns the count of key-value pairs.

Here’s the general syntax for employing the len() function with a dictionary:

len(dictionary)

Where "dictionary" is the variable representing the dictionary whose length we aim to determine.

len() method in Python Dictionary Examples

Let’s dive into some examples to better understand the Python Dictionary len() method in action:

Example#1 Basic Usage

my_dict = {"Name": "Alice", "Age": 30, "Profession": "Doctor"}
print(len(my_dict)) 

In the above example, the len() function yielded the number ‘3’, signifying the count of key-value pairs in the Python dictionary my_dict.

Output:

Python dictionary len method
Python dictionary len method

Example#2 Working with Nested Dictionaries

The len() function can also work with nested Python dictionaries. However, keep in mind that it counts only the top-level items. If we have a Python dictionary within a dictionary (nested dictionary), the len() function will treat the sub-dictionary as a single item.

multi_nested_dict = {
    "Name": "Alice",
    "Age": 30,
    "Education": {
        "High School": "Lincoln High",
        "University": {
            "Undergraduate": "Harvard University",
            "Graduate": "Yale University"
        }
    }
}
print(len(multi_nested_dict))  

Here, len() returns 3 because it counts top-level keys only. Even though the "University" key inside "Education" contains two more keys, len() sees "Education" as a single item in the main Python dictionary.

Output:

Python dictionary len method example
Python dictionary len method example

Conclusion:

The Python dictionary len() function offers a straightforward, rapid means of counting the number of items in a Python dictionary. It’s an invaluable tool when managing extensive datasets, assisting developers in swiftly assessing their data’s size.

Whether we’re a Python novice or a seasoned programmer, grasping and appropriately utilizing built-in functions like len() with Python dictionaries will dramatically enhance our coding efficiency and productivity.

You may also like to read the following articles: