How to Count the Number of Keys in a Python Dictionary?

Estimated read time 1 min read

You can count the number of keys in a Python dictionary using the len() function. The len() function returns the number of elements in an object, such as a list, tuple, or dictionary. Here’s an example:

# Input dictionary
my_dict = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}

# Get the number of keys in the dictionary
num_keys = len(my_dict)

# Print the number of keys
print(f"Number of keys in the dictionary: {num_keys}")

In this example, we first define the input dictionary my_dict with three key-value pairs. Then, we use the len() function to get the number of keys in the dictionary, and store the result in the num_keys variable. Finally, we print the number of keys using a print() statement. The len() function returns the count of keys in the dictionary, allowing you to easily determine the size of the dictionary.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply