Explain Codes LogoExplain Codes Logo

Counting the number of distinct keys in a dictionary in Python

python
dataframe
collections
best-practices
Anton ShumikhinbyAnton Shumikhin·Feb 3, 2025
TLDR

To count unique keys in a dictionary, employ the built-in function len():

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

The output is 3. As dictionaries inherently have unique keys, len() is completely efficient.

Inbuilt Efficiency: Single Line Solutions

For direct counting of distinct keys in a Python dictionary, simply apply the len() function on the dictionary:

# A simple way to count unique keys distinct_keys = len(your_dict)

Brevity is the soul of wit, and Python is darn witty! 🎭

Counting Unique Elements in Special Cases

Tackling Nested Structures

With nested structures or dictionaries with list values, you may wish to count unique items across all keys:

# Nested verbosity vs brevity battle nested_dict = {'a': [1, 2], 'b': [2, 3], 'c': [3, 4]} # Using a set to fight duplicates, and of course, len() to count unique_values = len({elem for sublist in nested_dict.values() for elem in sublist})

Python - Where even nested structures bow down to one-liners! 🐍

Unique Word Counting in Text Files

Apply the 'set and len()' concept to count unique words in a file:

# Counting unique words in a file distinct_words_in_file = len(set(open('your_file.txt').read().split()))

It's like one-liners have set up a permanent camp in Python. 🏕️

timeit - Your Performance Meter

For performance evaluation, the timeit module comes in super handy:

import timeit # Timing the time taken to count dictionary keys time_taken_to_count = timeit.timeit(lambda: len(your_dict), number=1000) print(f"Time elapsed: {time_taken_to_count} microseconds")

Time flies, but timeit outflies time! ⌚

Code Optimization: Accessories to Simplify Your Code

Exception Management

Implementing a try-except block can efficiently handle KeyError when a key doesn't exist:

# KeyError is like the Bogeyman of Python try: val = your_dict['missing_key'] except KeyError: print("Bogeyman alert! Key not found.")

Dictionary Comprehensions

When you need to create dictionaries from other data succinctly - enter dictionary comprehensions:

# Squaring only the even numbers, because why not? even_sq = {x: x**2 for x in range(10) if x % 2 == 0}

And if you want to reverse the dictionary mapping:

# Reversed dictionaries are still dictionaries reversed_dict = {val: key for key, val in your_dict.items()}

Also, they make your code look cooler. 😎