Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Counting the Number of Keys in a Dictionary

Python Counting the Number of Keys in a Dictionary

Document Object Reference Manual Python3 Examples

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

)

print

(

num_keys

)

Code analysis:

  1. my_dict = {'name': 'Alice', 'age': 25, 'city': 'New York'}: defines a dictionary my_dictcontaining three key-value pairs.
  2. num_keys = len(my_dict): When using len() function counts the keys in the dictionary my_dict and assigns the result to the variable num_keys。
  3. print(num_keys): print the variable num_keys 's value, that is, the number of keys in the dictionary.

Output result:

3

Document Object Reference Manual Python3 Examples