Middle
Milline on aja keerukus lisada ja eemaldada elementi Python sõnastikus?
sobes.tech AI
Vastus AI-lt
In Python, a dictionary is implemented based on a hash table, which provides an average time complexity of O(1) for adding and removing elements.
- Adding an element: the hash of the key is calculated, and the element is inserted into the corresponding cell. On average, this takes constant time.
- Removing an element: also performed via the hash of the key and takes on average O(1) time.
However, in the worst case (e.g., with many collisions), operations can degrade to O(n), where n is the number of elements in the dictionary, but such cases are extremely rare thanks to good implementation and dynamic resizing of the dictionary.
Example:
my_dict = {}
my_dict['key'] = 'value' # addition — O(1)
del my_dict['key'] # removal — O(1)