Back to Blog
Python

Python Dictionary Length: Using len() Correctly

Learn how to get the length of a Python dictionary with len(), what it counts, and common pitfalls to avoid.

pythondictionarylendata structuresperformance
Illustration of a Python dictionary with a length measurement.

To get the length of a Python dictionary, call the built-in len() function on the dictionary: len(d). It returns the number of key-value pairs the dictionary contains. This is a fundamental operation that appears in almost every Python program that uses dictionaries, whether you are validating input, iterating over data, or deciding whether to proceed with a computation.

Using len() to Get Dictionary Length

The len() function accepts any object that implements the __len__ method. Dictionaries implement it, so you can call len() directly on a dictionary instance:

user = {"name": "Ada", "role": "admin", "active": True} print(len(user)) # 3

There is no separate .length attribute or .size() method for dictionaries in Python. If you come from JavaScript or Java, you might be tempted to use user.length or user.size(), but those will raise AttributeError. The correct and only built-in way is len(user).

What len() Counts in a Dictionary

len() returns the number of entries in the dictionary, which is the same as the number of top-level keys. It does not look inside values: if a value is a collection, the elements in that collection are not counted.

inventory = { "apples": 5, "oranges": [1, 2, 3], "bananas": None } print(len(inventory)) # 3, not 5 or 6

Even though oranges is a list with three items, the dictionary has only three keys. If you need the total number of elements across all values, you must iterate and sum the lengths yourself.

Common Mistakes When Checking Dictionary Length

One frequent source of confusion is using dictionary views unnecessarily. len(d.keys()) and len(d.values()) both return the number of entries, but they are redundant because len(d) gives the same result. Prefer len(d) for clarity; it avoids an extra view object.

Another mistake is assuming that len() on a dictionary that contains nested dictionaries will count all nested keys. It does not. Only the top-level keys are counted.

data = { "user": {"name": "Ada", "age": 37}, "settings": {"theme": "dark"} } print(len(data)) # 2, not 4

If you need the total count of all keys in a nested structure, you must write a recursive function or use a third-party utility that flattens dictionary keys.

Checking for an Empty Dictionary

A common use of len() is to check whether a dictionary is empty. While len(d) == 0 works, the more idiomatic Python way is to use the dictionary directly in a boolean context:

config = {} if not config: print("No configuration provided")

An empty dictionary evaluates to False; a non-empty dictionary evaluates to True. This is more readable and avoids an explicit comparison. However, if you need to know the exact number of entries, len() is still the right tool.

Performance Characteristics of len()

For the built-in dict type, len() is O(1) in standard implementations. The dictionary tracks its size internally, so calling len() does not iterate over the keys. This means it is safe to call len() frequently, even on very large dictionaries, without worrying about performance degradation.

In contrast, iterating over the dictionary to count keys manually would be O(n) and should be avoided when you only need the size. For example, sum(1 for _ in d) is functionally equivalent but much slower for large dictionaries. The built-in len() is always the best choice.

Dictionary Length in Loops and Conditions

You often need the dictionary length to control loops or make decisions. For instance, you might want to process a dictionary until it reaches a certain size, or you might need to compare the lengths of two dictionaries:

if len(user_permissions) != len(required_permissions): raise ValueError("Permission mismatch")

In a loop, you can use len() to iterate a fixed number of times, but be careful: changing the number of keys while iterating directly over a dictionary raises a RuntimeError. If you need to iterate while removing items, collect the keys first or use a while loop with a condition based on len():

while len(task_queue) > 0: key = next(iter(task_queue)) process(task_queue.pop(key))

This pattern is useful when you want to drain a dictionary without creating a list of keys upfront.

Edge Cases and Custom Dictionary Subclasses

If you subclass dict and override __len__, len() will call your custom implementation. This can be useful for specialized behavior, but it also means that len() may not reflect the actual number of keys if you do not call super().__len__().

class CountingDict(dict): def __len__(self): return super().__len__() + 1 # always off by one d = CountingDict({"a": 1}) print(len(d)) # 2

In practice, you rarely need to override __len__. The default implementation is efficient and correct. If you do override it, make sure the returned value is consistent with the dictionary's actual contents, or you will confuse code that relies on len() for logic.

Another edge case is a dictionary with keys that are None or False. These are still counted normally. len({None: 1, False: 2}) returns 2 because both are distinct keys.

Finally, remember that len() works on any dictionary, including those created with comprehensions, dict() constructors, or loaded from JSON. There is no special handling needed.

Python Dictionary Length: Practical Usage and Code Examples | RYUSLOG DEV