Junior — Middle
Can you explain the structure and principles of a dictionary in Python?
sobes.tech AI
Answer from AI
A dictionary in Python is a mutable data structure that stores key-value pairs. It is based on a hash table, which provides fast access to values by key.
Main principles:
- Keys must be hashable (e.g., strings, numbers, tuples with immutable elements).
- When adding a key-value pair, the key is hashed, and the hash determines the index in the array.
- If a collision occurs (two keys with the same hash), Python uses open addressing to find the next free slot.
- When searching for a value by key, the key is hashed, and the keys are checked for an exact match.
Example of using a dictionary:
my_dict = {'apple': 5, 'banana': 3}
print(my_dict['apple']) # Outputs 5
my_dict['orange'] = 7 # Adding a new pair