Junior — Middle
How is the HashMap data structure implemented in Python, and how are its elements stored and searched?
sobes.tech AI
Answer from AI
In Python, a data structure similar to HashMap is implemented as a dictionary (dict). The dictionary is based on a hash table that stores key-value pairs.
How it works:
- The key passes through a hash function, which converts it into an array index (bucket).
- If there are already elements in this bucket (collision), Python uses open addressing with probing to find a free space.
- When searching for an element, the key is hashed, and the corresponding bucket is checked by index; if necessary, neighboring buckets are linearly probed.
Storage:
- Elements are stored in an array with a fixed size, which dynamically expands when a certain load factor is reached.
This provides an average complexity of insert, delete, and search operations close to O(1).
Example of using a dictionary:
my_dict = {'apple': 1, 'banana': 2}
print(my_dict['apple']) # Outputs 1