Sobes.tech
Junior — Middle

What is the time complexity of adding an element to a Dictionary data structure?

sobes.tech AI

Answer from AI

In Python, the data structure dict is implemented based on a hash table. On average, the operation of adding (inserting) an element into a dictionary has a time complexity of O(1) — that is, constant time.

However, in the worst case, due to hash collisions or the need to resize the internal array, the complexity can increase to O(n), where n is the number of elements in the dictionary. But such cases are rare and usually do not affect overall performance.

Example of adding an element to a dictionary:

my_dict = {}
my_dict['key'] = 'value'  # Addition operation with amortized complexity O(1)