Count Number of Keys in Dictionary Python

To count the number of keys in a Python dictionary, use the keys() method on the dictionary, then pass the result to the len() function.

 

Python Count Dictionary Keys Example

In the example below, we get all the keys in the dictionary using the keys() method then count how many there are using the len() function.

 

items = {'a':1,'b':2,'c':3}
print(len(items.keys()))
3

 

To get the distinct number of dictionary keys you can pass the dictionary directly to the len() function like this:

 

items = {'a':1,'b':2,'c':3}
print(len(items))
3