How to get the length of a dictionary in Python?

Published on Aug. 22, 2023, 12:17 p.m.

To get the length (i.e., the number of key-value pairs) of a Python dictionary, you can use the built-in len() function. Here’s an example:

my_dict = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
dict_length = len(my_dict)
print(dict_length)  # Output: 3

In this example, the len() function is used to get the length of the dictionary. The resulting number is stored in the dict_length variable and printed to the console.

Note that the length function in the search results example is different, as it returns the length of the dictionary when it’s treated as a list of its keys.

Tags: