Sobes.tech
Junior — Middle

Which is faster: searching by key in a dictionary or in a set in Python?

sobes.tech AI

Answer from AI

In Python, searching for a key in a dictionary (dict) and in a set (set) is implemented through hash tables and has an amortized complexity of O(1). Their speed is approximately the same.

However, a dictionary stores key-value pairs, while a set only stores keys. Therefore, searching for a key in a dictionary and checking for the presence of an element in a set are performed with the same efficiency.

Example:

my_dict = {'a': 1, 'b': 2}
my_set = {'a', 'b'}

# Search in dictionary
if 'a' in my_dict:
    print('Key found in dictionary')

# Search in set
if 'a' in my_set:
    print('Element found in set')

Conclusion: from a performance perspective, both search options are very fast and practically indistinguishable.