How to count the number of keys in a dictionary in Python

Dictionaries are very useful data structures in python that can hold a collection of items in the form of a key-value pair. This tutorial covers different methods by which we can count the number of keys in a dictionary in python.

Before moving towards this article, you should have a basic understanding of dictionaries, how they are created, their syntax and uses, etc. If you want to learn more about Python Tutorials, See this.

In order to count the number of keys in a dictionary in Python, we need to traverse over the dictionary using for loop. Initialize a count variable to 0 which increments on every iteration. The following are the methods used for counting the keys in a dictionary.

  • Method 1: Get number of keys in a Dictionary using for loop.
  • Method 2: Counting and printing number of keys in dictionary in python
  • Method 3: Use len() function to count and print keys.

method 1: using for loop to get no of keys in dictionary

#Program to find the total number of keys in a dictionary

def number_of_keys(dict):

    count = 0

    for key,value in dict.items():

        count += 1

    return count

No_of_fruits = {"Apple": 200, "Orange": 150, "Mango": 196, "Gauva": 128 }

print(count_keys(No_of_fruits))

Output:

4
 

In the above example, the function dict.items() returns the object items in the form of a (key, value) tuple. Here, the ‘key’ and ‘value’ variables iterate over the dictionary. You can also print them using the print(key) or print(value) command. if the two keys are the same, the program will count them as one.

method 2: count and print the number of keys in the dictionary in python

def number_of_keys(dict):

    count = 0

    for key,value in dict.items():

        count += 1

    return count

No_of_fruits = {"Apple": 200, "Orange": 150, "Orange": 196, "Gauva": 128 }

print(No_of_fruits.items())

print(count_keys(No_of_fruits))
 

Output:

dict_items([('Apple', 200), ('Orange', 196), ('Gauva', 128)])
3

The keys should be different otherwise the program will overwrite the previous value as shown in the above output window. Here, key ‘orange’ is repeated therefore dict.items() will overwrite 15 values by 196. That is why when you print the “No_of_fruits.items()” command, it prints (“Orange”: 196) pair. If you want to store multiple values in the same key, then you can do this by associating the value of a key with a list or a dictionary consisting of multiple values.

method 3: Use len() function to count the number of keys in a dictionary

The len() function is used to find the length of objects. It returns the total number of items. In dictionaries, the items are stored in the form of key-value pairs which means that the total number of items and keys are equal. Therefore, when len() function is applied to the dictionary, it returns the total number of keys.

Example 3:

Suppose you have a dictionary “No_of_fruits” which stores the name and quantity of fruits in a market and you want to count the keys or the different kinds of fruits that you have in a market.

 
No_of_fruits = {"Apple": 200, "Orange": 150, "Mango": 196, "Gauva": 128 }

print(len(No_of_fruits))
 

Output:

4

You can also apply this function directly on the keys. For this, extract all the keys of a dictionary using .key() method. Then, apply len() function which will return the total number of keys in the dictionary.

Example 4:

 
No_of_fruits = {"Apple": 200, "Orange": 150, "Mango": 196, "Gauva": 128 }

x=No_of_fruits.keys()

print(x)

print("Total number of keys: ", len(x))
 

Output:

dict_keys(['Apple', 'Orange', 'Mango', 'Gauva'])
Total number of keys:  4

In this case, the keys are distinct. For example 1, if the two keys are identical then the above code will return 3 as the total number of keys.

In this tutorial, you have learned how to count the total number of keys in a dictionary and what happens if the two keys are the same. If you have any queries, contact us. Let us know your feedback in the comments. It would be highly appreciated.

Leave a Comment

Your email address will not be published. Required fields are marked *