Python Counting the Number of Keys in a Dictionary
In Python, a dictionary is a very commonly used data structure made up of key-value pairs. Sometimes we need to know how many keys a dictionary has, which can be done with the len() function.
Example
my_dict
=
{
'name'
:
'Alice'
,
'age'
:
25
,
'city'
:
'New York'
}
num_keys
=
len
(
my_dict
)
(
num_keys
)
Code analysis:
my_dict = {'name': 'Alice', 'age': 25, 'city': 'New York'}: defines a dictionarymy_dictcontaining three key-value pairs.num_keys = len(my_dict): When usinglen()function counts the keys in the dictionarymy_dictand assigns the result to the variablenum_keys。print(num_keys): print the variablenum_keys's value, that is, the number of keys in the dictionary.
Output result:
3
Python3 Examples