Python Count the Number of Keys in a Dictionary

Document 对象参考手册Python3 Examples

In Python, a dictionary is a very commonly used data structure, composed of key-value pairs. Sometimes we need to know how many keys are in a dictionary, which can be done by using thelen()function.

Example

my_dict = {'name': 'Alice', 'age': 25, 'city': 'New York'}
num_keys = len(my_dict)
print(num_keys)

Code explanation:

  1. my_dict = {'name': 'Alice', 'age': 25, 'city': 'New York'}: defines a dictionarymy_dict, which contains three key-value pairs.
  2. num_keys = len(my_dict): use thelen()function to count the keys in the dictionarymy_dict, and assign the result to variablenum_keys。
  3. print(num_keys): print the variablenum_keys's value, that is, the number of keys in the dictionary.

Output result:

3

Document 对象参考手册Python3 Examples

Other extensions