Background:
Dictionaries (dict) are one of the basic data types in Python, representing a "key-value" structure. Dictionaries have been present since the very first Python release, but their internal implementation and behavior have been constantly improved (for example, in Python 3.7, the insertion order is guaranteed).
Problem:
Understanding the structure of a dictionary is necessary for writing efficient code. Without knowledge of the details, bugs can arise when using mutable types as keys, when copying nested dictionaries, and during unconventional operations.
Solution:
A dictionary is implemented as a hash table, and keys must be hashable (immutable). Accessing a value by key works close to O(1), but some conditions can lead to specific behaviors—such as collisions or when dealing with large datasets.
Example code:
person = {'name': 'Alice', 'age': 30} person['city'] = 'Moscow' print(person['name']) # Alice
Key features:
Can you use a list (list) as a key in a dict?
No, lists are mutable and not hashable. Attempting to use a list will raise an error.
d = {} d[[1, 2, 3]] = 'value' # TypeError: unhashable type: 'list'
What happens if you use two tuples with the same content as keys?
If both tuples contain the same data and are immutable, they are considered equal, and the keys in the dictionary will collide:
t1 = (1, 2) t2 = (1, 2) d = {t1: 'a'} print(d[t2]) # 'a'
Will the order of iteration over the dictionary elements change when copying?
In Python versions 3.7 and later, the order will be preserved. In older versions, the order of iteration is not guaranteed.
d1 = {'a': 1, 'b': 2} d2 = dict(d1) print(list(d2)) # ['a', 'b']
= does not create a copy but makes a new "pointer" to the same object.dict.get() without checking for None can lead to unexpected errors if the value == None.A programmer mistakenly uses lists as keys, believing that tuple and list are equivalent as keys in Python. They experience exceptions like "unhashable type".
Pros:
You can quickly try something "on the fly", using any structures.
Cons:
Runtime errors, bugs when processing data.
Only immutable (hashable) objects are used as keys, and tuples are designed not to contain mutable elements.
Pros:
Fast lookup by key, reliable structure, easy processing and copying.
Cons:
If the data is complex, additional processing is required to convert the structure to an immutable form (for example, serialization within a tuple).