Get the length of a Dictionary in Python

avatar

Borislav Hadzhiev

Tue Jun 14 20222 min read

banner

Photo by Fuu J

Get the length of a Dictionary in Python #

Use the len() function to get the length of 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.

main.py
my_dict = {'name': 'Alice', 'age': 30, 'tasks': ['dev', 'test']} # 👇️ get length of dict result_1 = len(my_dict) print(result_1) # 👉️ 3 # 👇️ get length of a value in the dictionary result_2 = len(my_dict['tasks']) print(result_2) # 👉️ 2

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.

If you need to get the length of a value in the dictionary, access the corresponding key and pass the result to the len() function.

main.py
my_dict = {'name': 'Alice', 'age': 30, 'tasks': ['dev', 'test']} # 👇️ get length of a value in the dictionary result_2 = len(my_dict['tasks']) print(result_2) # 👉️ 2

You can also create a new dictionary that maps the specific keys to the length of their values.

main.py
my_dict = {'name': 'Alice', 'tasks': ['dev', 'test']} len_values = {key: len((value)) for key, value in my_dict.items()} print(len_values) # 👉️ {'name': 5, 'tasks': 2} print(len_values['tasks']) # 👉️ 2

Note that this approach only works if all values in the dictionary can be passed to the len() function.

You can also use the len() function to check if a dictionary is empty.

main.py
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.

main.py
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.

main.py
my_dict = {} if not my_dict: # 👇️ this runs print('dict is empty') else: print('dict is NOT empty')
Use the search field on my Home Page to filter through my more than 1,000 articles.