Count the Number of Keys in a Dictionary in Python

To count the number of keys in a dictionary in Python:

my_dict = {"key_1": 1, "key_2": 2, "key_3": 3, "key_4": 4, "key_5": 5}

count_keys = len(my_dict)

print(count_keys)

Here, the result is 5 keys.

Count the number of keys in a nested dictionary

The following function can be used to count the number of keys in a nested dictionary:

def count_keys_of_dict(my_dict):
    count = 0
    for key, value in my_dict.items():
        count += 1
        if isinstance(value, dict):
            count += count_keys_of_dict(value)
    return count


my_nested_dict = {
    "key_1": 1,
    "key_2": {
        "key_3": 2,
        "key_4": {
            "key_5": 3,
            "key_6": 4,
            "key_7": 5
        }
    }
}

count_keys = count_keys_of_dict(my_nested_dict)

print(count_keys)

The result is 7 keys.

Leave a Comment