How to count distinct keys in a Python dictionary?

How can I count the number of distinct keys in a dictionary in Python dict count?

I have a dictionary where each keyword maps to its repetition count. However, I am only interested in the distinct keywords. Is there a way to count the number of distinct keys directly, or should I explore another approach to get the distinct keywords?

I’ve worked with Python dictionaries a lot, and one of the simplest ways is by using Python’s built-in len() function. It’s straightforward and efficient when counting keys in a dictionary. Here’s how it works:

data = {"apple": 3, "banana": 5, "cherry": 2}
distinct_key_count = len(data)
print(distinct_key_count)  # Output: 3

Explanation: The len() function calculates the number of keys directly. Since dictionaries inherently store unique keys, this gives you the exact count of distinct keys. A classic and quick way to handle a python dict count scenario.

Building on Tom’s answer, if you prefer being more explicit with accessing the dictionary keys, you can use the keys() method combined with len(). This approach can sometimes make your intention clearer in the code:

data = {"apple": 3, "banana": 5, "cherry": 2}
distinct_key_count = len(data.keys())
print(distinct_key_count)  # Output: 3

Explanation: The keys() method retrieves all the keys in the dictionary, and since Python dictionaries store only unique keys, passing them to len() gives the count. This method is slightly more verbose but ensures clarity when working with a python dict count operation.

Adding to @dimplesaini.230 suggestion, there are cases where your input structure might not guarantee uniqueness (e.g., after some preprocessing). In such cases, you can use a set() to eliminate any duplicates before counting. Here’s an example:

data = {"apple": 3, "banana": 5, "cherry": 2}
distinct_key_count = len(set(data.keys()))
print(distinct_key_count)  # Output: 3

Explanation: While Python dictionaries naturally avoid duplicate keys, converting to a set() ensures safety if there’s any unconventional input. This method is useful when handling edge cases and ensures accuracy in your python dict count calculations.