How to Count Keys in a Python Dictionary
This guide explains how to get the number of keys (which is the same as the number of key-value pairs) in a Python dictionary.
We'll cover the most direct method, using len(), and briefly discuss other less common approaches.
Using len() to Count Keys (Recommended)
The most straightforward and efficient way to count the number of keys in a dictionary is to use the built-in len() function directly on the dictionary:
my_dict = {
'name': 'Tom Nolan',
'age': 25,
'tasks': ['dev', 'test']
}
result = len(my_dict) # Directly on the dictionary
print(result) # Output: 3
len(my_dict): This directly returns the number of key-value pairs in the dictionary. This is the best way to get the count.
Using len(my_dict.keys()) (Redundant)
You might see code that uses len(my_dict.keys()). This works, but it's redundant:
my_dict = {'id': 1, 'name': 'Tom Nolan'}
print(my_dict.keys()) # dict_keys(['id', 'name']) # Creates a "view object"
print(len(my_dict.keys())) # Output: 2
my_dict.keys(): This returns a view object that represents the dictionary's keys. View objects are efficient, but you don't need to explicitly create one just to get the count.- The result will be the same as with just passing the dictionary to
len()
Using a for Loop (Inefficient)
You could use a for loop to count keys, but this is highly inefficient and unnecessary:
my_dict = {
'name': 'Tom Nolan',
'age': 25,
'tasks': ['dev', 'test']
}
count = 0
for key, value in my_dict.items():
count += 1
print(count) # Output: 3
-
The
dict.items()method returns a new view of the dictionary's items. -
This code manually iterates through the dictionary and increments a counter.
len(my_dict)does the same thing, but much faster and more clearly. Avoid this approach for simply counting keys.
Counting Keys that Satisfy a Condition
If you need to count keys based on some condition (e.g., keys whose values are greater than a certain number), use a generator expression with sum():
my_dict = {
'a': 1,
'b': 10,
'c': 100,
}
count = sum(1 for key, value in my_dict.items() if value > 5)
print(count) # Output: 2
sum(1 for ...): This is a concise way to count. The generator expression yields1for each key-value pair that meets the condition, andsum()adds them up.
Checking if a Dictionary is Empty
To check if a dictionary is empty, you can use len(my_dict) == 0, or, more simply, just use the dictionary itself in a boolean context (an empty dictionary is falsy):
my_dict = {}
if len(my_dict) == 0:
print('dict is empty') #Output: dict is empty
else:
print('dict is not empty')
# More concisely:
if not my_dict: # Empty dictionaries are "falsy"
print('dict is empty') # Output: dict is empty