Junior — Middle
Explain the functioning principle of a dictionary in Python and its internal structure.
sobes.tech AI
Answer from AI
In Python, a dictionary (dict) is a data structure that implements a key-value mapping with very fast search, insertion, and deletion operations.
Internally, the dictionary is implemented as a hash table. When adding a key-value pair, the key is hashed, and the hash determines the index in the array where the element is stored. If a collision occurs (two keys with the same hash), open addressing (probing) is used to find the next free cell.
Main points:
- Keys must be hashable (immutable types, e.g., strings, numbers, tuples).
- Values can be any objects.
- The dictionary dynamically expands when filled to maintain performance.
Example:
my_dict = {'apple': 5, 'banana': 3}
print(my_dict['apple']) # 5
my_dict['orange'] = 7
Thus, the dictionary provides quick access to data by key thanks to hashing.