Sobes.tech
Junior — Middle

What is the time complexity of searching for an element by key in a dictionary?

sobes.tech AI

Answer from AI

In Python, a dictionary (dict) is implemented based on a hash table, so the average time complexity for searching an element by key is O(1) (constant time).

This means that access to a value by key occurs very quickly, regardless of the size of the dictionary.

However, in the worst case (with a large number of hash collisions), the complexity can degrade to O(n), where n is the number of elements, but in practice, this happens very rarely thanks to good hash function implementations.

Example:

my_dict = {'apple': 1, 'banana': 2, 'cherry': 3}
value = my_dict['banana']  # Fast access, approximately O(1)
print(value)  # 2