Open In App

Get Total Keys in Dictionary – Python

Last Updated : 04 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

We are given a dictionary and our task is to count the total number of keys in it. For example, consider the dictionary: data = {“a”: 1, “b”: 2, “c”: 3, “d”: 4} then the output will be 4 as the total number of keys in this dictionary is 4.

Using len() with dict

The simplest way to count the total number of keys in a dictionary is by using the len() function directly on the dictionary since dictionaries store keys internally, len() returns the total number of keys.

Python
data = {"a": 1, "b": 2, "c": 3, "d": 4}
c = len(data)
print(c) 

Output
4

Explanation: len(data) directly returns the number of keys in the dictionary hence no need to extract keys separately making this the most efficient method.

Using len() with keys()

Another way to count the total number of keys is by using the keys() method which returns a view of all the dictionary keys and we then pass this view to len() to get the count.

Python
data = {"a": 1, "b": 2, "c": 3, "d": 4}
c = len(data.keys())
print(c)  

Output
4

Explanation:

  • data.keys() extracts all the keys from the dictionary and then len(data.keys()) then counts the total number of keys.
  • Although this method works, it is slightly less efficient than len(data) since keys() creates an additional view object.

Using Dictionary Unpacking with sum()

We can use dictionary unpacking in a generator expression along with sum() to count the total number of keys.

Python
data = {"a": 1, "b": 2, "c": 3, "d": 4}
c = sum(1 for _ in data)
print(c) 

Output
4

Explanation:

  • generator expression 1 for _ in data iterates over the dictionary keys and yields 1 for each key.
  • sum() adds up all the 1s, giving the total count of keys.
  • This method is an alternative to the loop but still not as efficient as len(data).

Using a Loop

We can manually count the total number of keys by iterating over the dictionary and maintaining a counter.

Python
data = {"a": 1, "b": 2, "c": 3, "d": 4}
c = 0

for key in data:
    c += 1

print(c) 

Output
4

Explanation:

  • We initialize count = 0 and the loop iterates over each key in the dictionary and increments count by 1.
  • Once the loop completes, count holds the total number of keys.
  • This method is useful when we want to process keys while counting them, but it’s less efficient than len(data).


Next Article
Practice Tags :

Similar Reads