How to count elements in a nested Python dictionary?

A nested dictionary is a dictionary inside another dictionary. In Python, we have the function len() to count elements in a nested dictionary. We can also use recursive functions to calculate elements at arbitrary depths within nested structures.

Non-Recursive Count in Nested Dictionary

A non-recursive count means counting only the keys at the top level, without going into any nested dictionaries. This approach uses the built-in len() function ?

# Define a nested dictionary
nested_dict = {
    "name": "Alice",
    "age": 30,
    "address": {
        "city": "New York",
        "zip": "10001"
    },
    "skills": {
        "programming": "Python",
        "database": "SQL"
    }
}

# Non-recursive count (top-level keys only)
top_level_count = len(nested_dict)

print("Top-level key count:", top_level_count)

The output of the above code is ?

Top-level key count: 4

Recursive Count of All Key-Value Pairs

To count all key-value pairs in a nested dictionary, we need a recursive function. This method counts elements at all nesting levels ?

def count_nested_elements(d):
    count = 0
    for key, value in d.items():
        count += 1  # Count the current key
        if isinstance(value, dict):
            count += count_nested_elements(value)  # Recurse into nested dict
    return count

# Sample nested dictionary
data = {
    "a": 1,
    "b": {
        "b1": 2,
        "b2": {
            "b21": 4,
            "b22": 5
        }
    },
    "c": 3
}

# Count all key-value pairs
total_count = count_nested_elements(data)

print("Total key-value pairs:", total_count)

The output of the above code is ?

Total key-value pairs: 7

Alternative Recursive Approach

Here's another recursive method that uses a counter parameter to track the total count across recursive calls ?

# Creating a nested dictionary
product_data = {
    "Product": {
        "Name": "Mobile",
        "Model": {
            'ModelName': 'Nord',
            'ModelColor': 'Silver',
            'ModelProcessor': 'Snapdragon'
        },
        "Units": 120,
        "Available": "Yes"
    }
}

# Function to calculate dictionary elements
def count_elements(data, counter=0):
    for key in data:
        if isinstance(data[key], dict):
            # Recursively count nested dictionary
            counter = count_elements(data[key], counter + 1)
        else:
            counter += 1
    return counter

# Display the nested dictionary
print("Nested Dictionary:")
print(product_data)

# Display the count of elements
print("Count of elements:", count_elements(product_data))

The output of the above code is ?

Nested Dictionary:
{'Product': {'Name': 'Mobile', 'Model': {'ModelName': 'Nord', 'ModelColor': 'Silver', 'ModelProcessor': 'Snapdragon'}, 'Units': 120, 'Available': 'Yes'}}
Count of elements: 8

Comparison of Methods

Method Counts Complexity Best For
len() Top-level keys only O(1) Simple dictionary structure
Recursive function All nested key-value pairs O(n) Deep nested structures

Conclusion

Use len() for counting top-level keys in nested dictionaries. For counting all key-value pairs across all nesting levels, implement a recursive function that traverses the entire dictionary structure.

Updated on: 2026-03-24T18:50:49+05:30

18K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements