Middle
What is the complexity of retrieving data by key in a dictionary?
sobes.tech AI
Answer from AI
In Python, a dictionary (dict) is implemented based on a hash table, so retrieving a value by key usually has an amortized time complexity of O(1) — meaning the operation is performed in constant time on average.
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 in the dictionary. But thanks to good implementation and dynamic resizing of the dictionary, such situations are extremely rare.
Example:
my_dict = {'a': 1, 'b': 2, 'c': 3}
value = my_dict['b'] # Retrieval by key in O(1)