How to Count the Number of Keys in a Python Dictionary

Python’s built-in len() is all you need: to count the number of keys in a Python dictionary, pass the dictionary to len() and it returns the key total instantly, because a dict keeps that number on hand.

prices = {"laptop": 899.99, "mouse": 24.95}
len(prices)  # 2

Every result on this page came straight out of a Command Prompt window running Python 3.12.5.

In this tutorial, we’ll count keys that pass a test, total the keys inside nested dictionaries, tally keys across a list of records, and see how updates move the count.

Count dictionary keys with len()

Here’s a small store inventory. I count it with len() directly and through the keys() view, then check an empty dictionary:

inventory = {"laptop": 899.99, "monitor": 249.50, "keyboard": 49.99, "mouse": 24.95}

print(len(inventory))          # number of keys
print(len(inventory.keys()))   # same answer through the keys view

empty = {}
print(len(empty))
if not empty:
    print("No keys yet")

Output:

4
4
0
No keys yet
Command Prompt output of Python len() returning 4 for an inventory dictionary, 4 for its keys view and 0 for an empty dictionary
Both calls report four keys, and the empty dictionary reports zero.

len(d.keys()) works but builds a view you don’t need, and an empty dict is falsy. For how len() treats other containers, see my guide to finding the length of a Python dictionary.

Count only the keys that match a condition

Sometimes you don’t want every key, just the ones that pass a test. Feed a generator of 1s to sum():

inventory = {"laptop": 899.99, "monitor": 249.50, "keyboard": 49.99, "mouse": 24.95}

over_50 = sum(1 for price in inventory.values() if price > 50.00)
print("Items over $50.00:", over_50)

m_keys = sum(1 for name in inventory if name.startswith("m"))
print("Keys starting with m:", m_keys)

Output:

Items over $50.00: 2
Keys starting with m: 2

The first test looks at values and the second at the key names themselves. Both make one pass; iterating through a Python dictionary explains keys(), values() and items() in more depth.

How do I count keys in a nested dictionary?

len() only sees the top level. To include the keys of inner dictionaries, recurse into any value that is itself a dict:

staff = {
    "Sales": {"Megan Bowen": "Manager", "Adele Vance": "Rep"},
    "IT": {"Alex Wilber": "Admin", "Lee Gu": "Developer", "Grady Archie": "Analyst"},
    "HR": {},
}

def count_keys(d):
    total = 0
    for value in d.values():
        total += 1
        if isinstance(value, dict):
            total += count_keys(value)
    return total

print("Top-level keys:", len(staff))
print("All keys, every level:", count_keys(staff))
print({dept: len(people) for dept, people in staff.items()})

Output:

Top-level keys: 3
All keys, every level: 8
{'Sales': 2, 'IT': 3, 'HR': 0}
Command Prompt output of a recursive Python function counting 3 top-level and 8 total keys in a nested staff dictionary, plus per-department counts
Three departments at the top level, eight keys in total, and HR counted even though it’s empty.

The function counts the department key first, then adds whatever lives inside it. When you read deep values rather than count them, handling KeyError in a nested Python dictionary keeps missing levels from crashing your code.

Count how often each key appears in a list of dictionaries

API records rarely share the same fields. collections.Counter tallies every key in one line:

from collections import Counter

orders = [
    {"id": 5001, "total": 120.00, "coupon": "FALL10"},
    {"id": 5002, "total": 64.25},
    {"id": 5003, "total": 310.40, "coupon": "VIP", "gift_wrap": True},
]

key_counts = Counter(key for order in orders for key in order)
print(key_counts)
print("coupon used in", key_counts["coupon"], "of", len(orders), "orders")

unique = set().union(*orders)
print("Distinct keys:", len(unique))

Output:

Counter({'id': 3, 'total': 3, 'coupon': 2, 'gift_wrap': 1})
coupon used in 2 of 3 orders
Distinct keys: 4
Command Prompt output of Python Counter tallying id, total, coupon and gift_wrap keys across three order dictionaries and printing 4 distinct keys
Every order has id and total, two carry a coupon, and only one asks for gift wrap.

set().union(*orders) answers the related question of how many distinct keys exist at all. If you need the key names themselves rather than a number, read getting the keys of a dictionary in Python.

Does updating a dictionary change its key count?

Only adding or removing keys moves the number. Assigning to a key that already exists swaps the value in place:

scores = {"Boston": 88, "Denver": 92}
print(len(scores))

scores["Boston"] = 95        # existing key: value changes, count stays
print(len(scores))

scores["Austin"] = 79        # new key: count goes up
print(len(scores))

del scores["Denver"]
print(len(scores))

try:
    scores.count()
except AttributeError as e:
    print("AttributeError:", e)

Output:

2
2
3
2
AttributeError: 'dict' object has no attribute 'count'
Command Prompt output showing a Python dictionary key count staying at 2 after an update, rising to 3 after a new key, dropping to 2 after del, and the AttributeError for count()
The count holds at two after the update, climbs to three, then falls back to two after the delete.

Note the last line: dictionaries have no count() method, so stick with len(). My post on updating values in a Python dictionary covers update() and other ways to change values safely.

Building the dictionary in a loop? creating a dictionary in Python with a for loop shows the pattern.

Which key-counting method fits your data?

You wantUseNotes
All top-level keyslen(d)Constant time
Keys passing a testsum(1 for k in d if test)One pass
Keys at every levelRecursive functionChecks isinstance(v, dict)
Key frequency across recordsCounter(k for r in rows for k in r)Missing keys show as 0
Distinct keys across recordslen(set().union(*rows))Ignores repeats

Want to keep practicing with dictionaries? Try these next:

Frequently asked questions

How do I count the number of keys in a Python dictionary?

Call len(d). It returns the number of top-level keys without looping.

Is len(d.keys()) faster than len(d)?

No. Both return the same number, but len(d) skips creating the keys view.

Does len() count keys inside nested dictionaries?

No. It counts only the top level; use a recursive function to include inner keys.

Why does my dictionary have no attribute ‘count’?

Dictionaries don’t have a count() method. Use len() for keys or Counter for frequencies.

How do I count keys with a specific value?

Use sum(1 for v in d.values() if v == target).

Where is len() for dictionaries documented?

See dict in the Python docs.