Count the number of Keys in a Dictionary in Python


Borislav Hadzhiev

Last updated: Jun 14, 2022


Photo from Unsplash

Count the number of Keys in a Dictionary in Python #

Use the len() function to count the number of keys in a dictionary, e.g. result = len(my_dict). The len() function can be passed a collection such as a dictionary and will return the number of key-value pairs in the dictionary, which is the same as the number of keys.
my_dict = {'name': 'Alice', 'age': 30, 'tasks': ['dev', 'test']} result_1 = len(my_dict) print(result_1) # 👉️ 3 result_2 = len(my_dict.keys()) print(result_2) # 👉️ 3

The len() function returns the length (the number of items) of an object.

The argument the function takes may be a sequence (a string, tuple, list, range or bytes) or a collection (a dictionary, set, or frozen set).

The first example shows how to get the number of key-value pairs in the dictionary.

The number of keys and values in the dictionary is the same, so passing the entire dictionary to the len() function is sufficient.

The dict.keys method returns a new view of the dictionary's keys.
my_dict = {'id': 1, 'name': 'Alice'} print(my_dict.keys()) # 👉️ dict_keys(['id', 'name']) print(len(my_dict.keys())) # 👉️ 2

You can use the list() class if you need to convert the view of keys into a list.
my_dict = {'id': 1, 'name': 'Alice'} list_of_keys = list(my_dict.keys()) print(list_of_keys) # 👉️ ['id', 'name'] print(len(list_of_keys)) # 👉️ 2

Note that passing the dictionary directly to the len() function is a little faster than creating a view object via the dict.keys() method and passing the view to the len() function.

You can also use the len() function to check if a dictionary is empty.
my_dict = {} if len(my_dict) == 0: # 👇️ this runs print('dict is empty') else: print('dict is not empty')

If a dictionary has a length of 0, then it's empty.

You might also see examples online that check whether the dictionary is truthy (to check if it contains at least 1 key-value pair), which is more implicit.
my_dict = {} if my_dict: print('dict is NOT empty') else: # 👇️ this runs print('dict is empty')

All values that are not truthy are considered falsy. The falsy values in Python are:

  • constants defined to be falsy: None and False.
  • 0 (zero) of any numeric type
  • empty sequences and collections: "" (empty string), () (empty tuple), [] (empty list), {} (empty dictionary), set() (empty set), range(0) (empty range).

Notice that an empty dictionary is a falsy value, so if the dict is empty, the else block is ran.

If you need to check if the dictionary is empty using this approach, you would negate the condition with not.
my_dict = {} if not my_dict: # 👇️ this runs print('dict is empty') else: print('dict is NOT empty')
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.