Last Updated : 12 Jul, 2025
Python provides multiple methods to get the length, and we can apply these methods to both simple and nested dictionaries. Let’s explore the various methods.
Using Len() FunctionTo calculate the length of a dictionary, we can use Python built-in len() method. It method returns the number of keys in dictionary.
Python
d ={'Name':'Steve', 'Age':30, 'Designation':'Programmer'}
print(len(d))
Let's explore other methods of getting length of a dictionary in python:
Using List ComprehensionAnother less common method is to use a list comprehension, which can also be used to count the number of keys in a dictionary.
Example:
Python
d = {"a": 1, "b": 2, "c": 3}
length = len([key for key in d])
print(length)
Explanation:
We can also use the sum() function to count the number of items in a dictionary by adding 1 for each key-value pair.
Example:
Python
d = {"a": 1, "b": 2, "c": 3}
length = sum(1 for i in d)
print(length)
Getting length of nested dictionary
When working with nested dictionaries, we may want to count only the top-level keys or count the keys in nested dictionaries. If we want to get the length of the top-level dictionary, len() works just as it does with simple dictionaries.
Python
d = {
"person1": {"name": "John", "age": 25},
"person2": {"name": "Alice", "age": 30},
"person3": {"name": "Bob", "age": 22}
}
length = len(d)
print(length)
Explanation:
Another method to count items in a dictionary, including nested dictionaries, is using a loop. For nested dictionaries, we can manually iterate through all the nested keys and values.
Python
d = {
"product1": {"name": "Laptop", "price": 800, "stock": 15},
"product2": {"name": "Smartphone", "price": 500, "stock": 30},
"product3": {"name": "Tablet", "price": 300, "stock": 25}
}
cnt = 0
# Loop through the top-level dictionary
for key, val in d.items():
if isinstance(val, dict): # Check if the value is a nested dictionary
# Loop through the nested dictionary
for i in val:
cnt += 1 # Count each key in the nested dictionary
else:
cnt += 1 # Count the top-level keys
print(cnt)
Explanation:
We can also use the len() function on the dictionary’s keys, values or items to determine the number of keys, values or key-value pairs.
Python
d = {"a": 1, "b": 2, "c": 3}
# Number of Keys
length = len(d.keys())
print(length)
# Number of Values
length = len(d.values())
print(length)
# Number of Items
length = len(d.items())
print(length)
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4