Junior — Middle
How to determine the time complexity of dictionary operations?
sobes.tech AI
Answer from AI
The time complexity of the main operations with a dictionary (dict) in Python is usually amortized O(1) for insertion, deletion, and key lookup. This is achieved through the use of a hash table. However, in the worst case (for example, with many collisions), the complexity can degrade to O(n).
Example:
my_dict = {'a': 1, 'b': 2}
# Key lookup
value = my_dict.get('a') # O(1)
# Insertion
my_dict['c'] = 3 # O(1)
# Deletion
del my_dict['b'] # O(1)
Thus, dictionary operations are very efficient and suitable for fast data access by key.