Eq () and hash () in Python: Difference between revisions
Jump to navigation
Jump to search
Line 12: | Line 12: | ||
===Dictionaries and the <tt>__hash__()</tt> Function=== | ===Dictionaries and the <tt>__hash__()</tt> Function=== | ||
To store a key into a dictionary, Python performs the following sequence: | To store a key into a [[Python_Language_Dictionary#Dictionaries_and_the_hash_.28.29_Function|dictionary]], Python performs the following sequence: | ||
1. Call <code>__hash__()</code> on the key and compute the hash of the key. If the key is not hashable, raise a <code>TypeError</code>. | 1. Call <code>__hash__()</code> on the key and compute the hash of the key. If the key is not hashable, raise a <code>TypeError</code>. |
Revision as of 16:16, 11 September 2022
Internal
Overview
__eq__()
__hash__()
Dictionaries and the __hash__() Function
To store a key into a dictionary, Python performs the following sequence:
1. Call __hash__()
on the key and compute the hash of the key. If the key is not hashable, raise a TypeError
.
2. Store (hash_value, key, value) in the bucket at the location hash_value % len(buckets)
3. If the bucket array needs resizing, __re-use the previously computed hash value__ to re-insert all previously stored values. This is why is important that the key is immutable: if the key is mutable and it changes while the key/value pair is stored in the dictionary, lookup and resizing will not work.