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. With that, we can also use a function that recursively calls and calculates the elements in an arbitrary depth of the nested dictionary.

Non-Recursive Count in Nested Dictionary

A non-recursive count in a nested dictionary means counting only the keys at the top level, without going into any nested dictionaries inside it. Here is an example of counting the elements in a nested python dictionary-

# 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)

Here is the output of the above program -

Top-level key count: 4

Recursive Count of All Key-Value Pairs

In a nested dictionary to count all key-value pairs, we have to use a recursive function. This method is used to count all levels of nested elements in the dictionary. Following is the example to perform the Recursive count of all Key-Value pairs in a nested dictionary -

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)

Following is the output of the above program -

Total key-value pairs: 7

Count Elements in an Arbitrary Depth

To count all key-value pairs in a nested dictionary of arbitrary depth, we should use a recursive approach. This allows us to drill into each level of the structure, no matter how deeply nested it is. Below is the example, which counts elements in an Arbitrary depth of a Nested Dictionary -

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

# Function to calculate the Dictionary elements
def count(prod, c=0):
	for mykey in prod:
		if isinstance(prod[mykey], dict):
			# calls repeatedly
			c = count(prod[mykey], c + 1)
		else:
			c += 1
	return c

# Displaying the Nested Dictionary
print("Nested Dictionary = \n",myprod)

# Display the count of elements in the Nested Dictionary
print("Count of the Nested Dictionary = ",count(myprod))

Here is the output of the above example -

Nested Dictionary =
 {'Product': {'Name': 'Mobile', 'Model': {'ModelName': 'Nord', 'ModelColor': 'Silver', 'ModelProcessor': 'Snapdragon'}, 'Units': 120, 'Available': 'Yes'}}
Count of the Nested Dictionary =  8
Updated on: 2025-06-10T17:44:49+05:30

18K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements