How to count distinct keys in a Python dictionary?

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.