Back to series
· 14 min read

Python Hashing Mechanism and Dictionary Key Requirements


I. What Is Hashing

Hashing is a technique that maps data to fixed-length integers. A hash function takes an object and computes the corresponding hash value so that data structures can quickly locate and manage elements.

Python provides a built-in function:

hash(object)

For example:

print(hash(100))
print(hash("Python"))
print(hash((1, 2, 3)))

Different objects may produce different hash values, but note the following:

  • A hash value is an integer and does not represent the object itself.
  • The same object should have a consistent hash value within the same run.
  • Different objects may have the same hash value.
  • Hash values are not guaranteed to be unique.
  • Some objects are unhashable, and calling hash() raises TypeError.

The core goal of hashing is not to directly determine whether two objects are equal, but to help a hash table quickly narrow the search range.

1. The Basic Process of Hashing

The hash mechanism can be understood as the following process:

Input object
   |
   v
Compute hash value
   |
   v
Locate storage location based on hash value
   |
   v
Check target location
   |
   v
Compare objects for equality if necessary
   |
   v
Complete lookup or storage

For example, using a dictionary to store user information:

users = {
    "alice": 1001,
    "bob": 1002,
    "charlie": 1003
}

print(users["alice"])

Python can use the key's hash value to quickly locate the position where the key-value pair may be stored, then use an equality check to confirm whether the target key has been found.

2. Difference Between Hash Values and Object Identity

Hash value, object identity, and object value are three different concepts.

Concept Meaning Common Operation
Object value The data content represented by the object ==
Object identity Whether it is the same object is
Hash value The hash integer corresponding to the object hash()

For example:

a = "Python"
b = "Python"

print(a == b)
print(a is b)
print(hash(a))
print(hash(b))

Generally:

  • a == b is True because the string contents are the same.
  • a is b should not be used as a basis for determining value equality.
  • Two equal strings must have the same hash value.

Optimizations such as string interning and object reuse may affect object identity, so you should not rely on is to determine whether ordinary strings, integers, and similar value objects are equal.

II. Hash Functions and Hash Values

A hash function is responsible for mapping objects to integers.

Python objects can provide hash behavior through the __hash__() method.

For example:

text = "Python"

print(text.__hash__())
print(hash(text))

For a normally implemented object, the two correspond to its hash behavior.

However, in everyday development, you should prefer the built-in hash() function rather than calling the special method directly.

1. Basic Characteristics of Hash Functions

A hash function suitable for use with hash tables usually needs to have the following characteristics:

Determinism

Within the same program run, an object's hash value should remain stable.

text = "Python"

print(hash(text))
print(hash(text))

As long as the state of the object involved in hashing does not change, the two results should be the same.

Distribution

The hash values of different objects should be distributed as evenly as possible to reduce hash collisions.

Efficiency

Hash computation must not be too complex; otherwise, it increases the operation cost of dictionaries and sets.

Equal Objects Have the Same Hash

This is the most important constraint of Python's hashing mechanism:

If two objects are equal, they must have the same hash value.

a == b \Rightarrow hash(a) == hash(b)

The converse does not hold:

hash(a) == hash(b) \not\Rightarrow a == b

In other words, having the same hash value does not mean the objects are necessarily equal.

2. Hash Values Are Not Unique

Suppose there are two different objects:

a = "apple"
b = "orange"

They may have different hash values, or they may theoretically have a hash collision.

The output space of a hash function is finite, while the number of possible input objects is enormous, so different objects mapping to the same hash value cannot be completely avoided.

This situation is called a hash collision.

3. Hash Values Should Not Be Used as Permanent Identifiers

The following approach is not suitable for generating permanent business IDs:

user_id = hash("alice")

The reasons include:

  • The hash values of strings and byte strings are affected by randomization by default.
  • Hash values may differ between processes.
  • They are not guaranteed to be the same across Python versions or implementations.
  • Different objects may collide in hash values.

If you need a permanent, stable identifier, use a database primary key, a UUID, or a deliberately designed stable digest algorithm instead of Python's built-in hash().

III. What Is a Hashable Object

Not all objects in Python can take part in hashing.

A hashable object is an object that can provide a valid hash value and, throughout its lifetime, satisfies the constraints between hashing and equality.

Dictionary keys and set elements in Python must all be hashable objects.

For example:

print(hash(100))
print(hash("Python"))
print(hash((1, 2, 3)))

These objects can normally have their hash values computed.

The following code, however, raises an error:

hash([1, 2, 3])

Exception:

TypeError: unhashable type: 'list'

The reason is that a list is a mutable object, and a list's contents can change.

1. Common Hashable Types

Type Hashable Notes
int Yes Integers are immutable
float Yes Floats are hashable
complex Yes Complex numbers are hashable
bool Yes Booleans are a subclass of integers
str Yes Strings are immutable
bytes Yes Byte sequences are immutable
NoneType Yes None can be used as a dictionary key
tuple Conditional All elements must be hashable
frozenset Conditional All elements must be hashable
list No Lists are mutable
dict No Dictionaries are mutable
set No Sets are mutable
bytearray No Byte arrays are mutable

Note that tuples and frozen sets are not unconditionally hashable.

For example:

print(hash((1, 2, 3)))

This runs normally.

But:

hash((1, [2, 3]))

produces:

TypeError: unhashable type: 'list'

because the tuple contains a list, which is not hashable.

2. Why Mutable Objects Are Usually Not Hashable

Suppose a list could be used as a dictionary key:

key = [1, 2, 3]

If the list's contents change:

key.append(4)

then the state that goes into its hash computation may also change.

If the object is already stored in a hash table, but a lookup uses the new hash value, the original storage location may no longer be found.

This breaks the invariants of the hash table data structure.

For this reason, Python's built-in lists, dictionaries, and sets are not allowed as dictionary keys.

3. Immutable Objects Are Not Necessarily Hashable

Immutability and hashability are not exactly the same concept.

For example:

data = (1, [2, 3])

A tuple itself cannot change the references to its elements, but the inner list can still be modified.

Therefore:

print(hash(data))

raises an error.

The correct understanding:

  • Immutability describes whether an object can change its own state.
  • Hashability describes whether an object can safely take part in hash table operations.
  • For composite objects, all internal state that participates in hashing must be checked.

IV. Why Dictionaries Require Keys to Be Hashable

A dictionary (dict) is a mapping type implemented on top of a hash table.

It maps keys to their corresponding values:

user = {
    "name": "Alice",
    "age": 25,
    "city": "Beijing"
}

A dictionary uses the hash value of a key to help locate the key-value pair.

1. The basic structure of a dictionary

A dictionary can be understood as:

键 Key
  |
  v
计算哈希值
  |
  v
定位哈希表位置
  |
  v
保存键和值

For example:

user = {
    "name": "Alice"
}

When executing:

print(user["name"])

Python locates the possible storage position based on the hash value of "name", then checks whether the keys are equal, and finally retrieves the corresponding value.

2. Why dictionary keys cannot be lists

user = {
    [1, 2, 3]: "Alice"
}

When executed, it raises:

TypeError: unhashable type: 'list'

Because a list cannot provide the stable hash behavior that is required.

If you need to use multiple values to form a composite key, you can consider using a tuple:

locations = {
    (39.9042, 116.4074): "Beijing",
    (31.2304, 121.4737): "Shanghai"
}

As long as all elements in the tuple are hashable, it can be used as a dictionary key.

3. Dictionary values do not need to be hashable

It is important to distinguish between keys and values.

data = {
    "numbers": [1, 2, 3],
    "profile": {
        "name": "Alice"
    },
    "tags": {"python", "backend"}
}

This dictionary is completely valid.

Because:

  • Dictionary keys must be hashable.
  • Dictionary values can be any Python object.

Values can be lists, dictionaries, sets, custom objects, or even another dictionary.

V. Hash collision mechanisms

A hash collision refers to different objects producing the same hash value after being processed by a hash function, or mapping to the same storage position during hash table lookup.

For example:

a = "apple"
b = "orange"

Suppose two objects have a hash collision; the dictionary must still be able to distinguish them.

Therefore, a hash table cannot rely solely on hash values to determine whether keys are equal.

1. The same hash value does not mean objects are equal

class Key:
    def __init__(self, value):
        self.value = value

    def __hash__(self):
        return 1

    def __eq__(self, other):
        if not isinstance(other, Key):
            return NotImplemented

        return self.value == other.value


a = Key("apple")
b = Key("orange")

print(hash(a))
print(hash(b))
print(a == b)

Output:

1
1
False

The two objects have the same hash value but different contents, so they are not equal.

2. How dictionaries handle hash collisions

When multiple keys have hash collisions, the dictionary needs further handling and cannot simply overwrite existing data.

Conceptually, this can be understood as:

  1. Find candidate positions based on the hash value.
  2. Check whether the candidate position is empty.
  3. If the position already has an element, compare the hash values and the equality of the keys.
  4. If the keys are equal, consider the same logical key found.
  5. If the keys are not equal, continue looking for other available positions.
  6. Until the target key or an available position is found.

Flowchart:

flowchart TD
    A["Receive dictionary key"] --> B["Compute the key's hash value"]
    B --> C["Locate candidate storage location"]
    C --> D{"Does a key exist at the position?"}
    D -->|No| E["Insert key-value pair"]
    D -->|Yes| F["Check hash value and key equality"]
    F --> G{"Is it the same logical key?"}
    G -->|Yes| H["Update the corresponding value"]
    G -->|No| I["Continue probing other positions"]
    I --> J{"Is an available position found?"}
    J -->|Yes| E
    J -->|No| K["Expand the hash table and rearrange"]
    K --> C
    E --> L["Operation complete"]
    H --> L

    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style C fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style D fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style E fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style F fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style G fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style H fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style I fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style J fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style K fill:#FBE9E9,stroke:#D9AAAA,color:#334155
    style L fill:#E8EDF2,stroke:#B8C3CE,color:#334155
    linkStyle default stroke:#A3B8AC,stroke-width:1.5px

This is a conceptual flow of hash table collision handling, not a step-by-step diagram of the probing algorithm inside CPython dictionaries.

3. Hash Collisions and Equality Checks

A hash table needs to use both hash values and equality checks.

Core relationships:

  • Different hash values: two objects cannot satisfy equality under the hash contract.
  • Same hash value: two objects may or may not be equal.
  • Equal objects: their hash values must be the same.

Therefore, dictionary lookup is not simply comparing hash values.

6. Python's hash() and eq()

Python allows custom objects to define hashing behavior and equality behavior through special methods.

The two most important methods are:

  • __hash__(): returns the object's hash value.
  • __eq__(): determines whether two objects are equal.

Together they determine whether a custom object can safely be used as a dictionary key or set element.

1. The hash() Method

__hash__() is used to define an object's hashing behavior.

For example:

class User:
    def __init__(self, user_id):
        self.user_id = user_id

    def __hash__(self):
        return hash(self.user_id)


user = User(1001)

print(hash(user))

Here, the user ID is used to compute the object's hash value.

Note that __hash__() must return an integer, and the hash value must satisfy the stability required by object equality.

2. The eq() Method

__eq__() is used to define value equality between objects.

class User:
    def __init__(self, user_id):
        self.user_id = user_id

    def __eq__(self, other):
        if not isinstance(other, User):
            return NotImplemented

        return self.user_id == other.user_id


a = User(1001)
b = User(1001)

print(a == b)

Output:

True

Two different object instances can be considered to have the same logical value as long as their user IDs are the same.

3. Why the Two Methods Need to Work Together

If only __eq__() is implemented and __hash__() is not implemented correctly, the object may not be usable as a dictionary key.

For example:

class User:
    def __init__(self, user_id):
        self.user_id = user_id

    def __eq__(self, other):
        if not isinstance(other, User):
            return NotImplemented

        return self.user_id == other.user_id


user = User(1001)

print(user == User(1001))
print(hash(user))

When a class defines its own __eq__() but does not explicitly provide a compatible __hash__(), Python usually sets that class's __hash__ to None, making its instances unhashable.

This is a safeguard Python uses to prevent incorrect hashing behavior.

4. The Correct Implementation for Custom Objects

class User:
    def __init__(self, user_id, name):
        self.user_id = user_id
        self.name = name

    def __eq__(self, other):
        if not isinstance(other, User):
            return NotImplemented

        return self.user_id == other.user_id

    def __hash__(self):
        return hash(self.user_id)


a = User(1001, "Alice")
b = User(1001, "Alice")

print(a == b)
print(hash(a) == hash(b))

users = {
    a: "管理员"
}

print(users[b])

Output:

True
True
管理员

Although a and b are two different instances, they have the same user ID, so under the current definition they belong to the same logical key.

VII. Python's Hash Contract

When writing custom hashable objects, you must follow Python's hash contract.

This is the most important rule when designing dictionary keys and set elements.

1. Equal Objects Must Have the Same Hash Value

The following must hold:

a == b \Rightarrow hash(a) == hash(b)

For example:

class User:
    def __init__(self, user_id):
        self.user_id = user_id

    def __eq__(self, other):
        if not isinstance(other, User):
            return NotImplemented

        return self.user_id == other.user_id

    def __hash__(self):
        return hash(self.user_id)


a = User(1001)
b = User(1001)

print(a == b)
print(hash(a) == hash(b))

If two objects are equal but have different hash values, dictionaries and sets may fail to recognize them as the same logical key.

2. Equal Hashes Do Not Require Equal Objects

The following does not need to hold:

hash(a) == hash(b) \Rightarrow a == b

Because hash collisions are permitted.

For example:

class Number:
    def __init__(self, value):
        self.value = value

    def __hash__(self):
        return 1

    def __eq__(self, other):
        if not isinstance(other, Number):
            return NotImplemented

        return self.value == other.value


a = Number(10)
b = Number(20)

print(hash(a) == hash(b))
print(a == b)

Output:

True
False

Even though the hash values are the same, the two objects are still not equal.

3. The Hash Value Must Remain Stable Throughout the Object's Lifetime

If an object is already being used as a dictionary key or set element, the state involved in computing its hash must not change arbitrarily.

For example:

class User:
    def __init__(self, user_id):
        self.user_id = user_id

    def __hash__(self):
        return hash(self.user_id)

    def __eq__(self, other):
        if not isinstance(other, User):
            return NotImplemented

        return self.user_id == other.user_id

Suppose:

user = User(1001)

data = {
    user: "Alice"
}

If it is subsequently modified:

user.user_id = 2002

The object's hash value may change.

But the dictionary originally arranged storage based on the old hash value, so lookups may no longer locate it correctly.

For example:

print(data.get(user))

may not produce the expected result.

This would break normal dictionary usage, so the key state involved in hashing must not change while the object is used as a key.

4. Summary of the Hash Contract

Rule Must Be Satisfied Description
Equal objects have the same hash value Required Core of the hash contract
Objects with the same hash value are equal Not required Hash collisions are allowed
The same object identity has the same hash value Required by the hash contract The same object is necessarily equal to itself
The hash value never changes Not required Not guaranteed across processes or runs
Hash state remains stable while used as a key Required Ensures the hash table can look up correctly
The hash function is as uniform as possible Strongly recommended Reduces collisions and improves performance

8. Why True, 1, and 1.0 Are the Same Key in a Dictionary

This is a very typical point in Python's hashing mechanism.

In Python:

print(True == 1)
print(1 == 1.0)
print(True == 1.0)

Result:

True
True
True

Their hash values are also the same:

print(hash(True))
print(hash(1))
print(hash(1.0))

Therefore:

data = {
    True: "boolean",
    1: "integer",
    1.0: "float"
}

print(data)
print(len(data))

Result:

{True: 'float'}
1

Under equality checks and hashing rules, the three keys are the same logical key, so later assignments update the corresponding value.

1. Dictionary Keys Do Not Depend Solely on Type

A dictionary does not treat two objects as different keys merely because their types differ.

A dictionary cares more about:

  • Whether the hash values match.
  • Whether the keys are equal.

As long as two objects are equal and their hash values match, they may be treated as the same dictionary key.

2. Caveats in Business Logic

If the business logic must distinguish booleans, integers, and floats, the type needs to be explicitly included in the key design.

For example:

def make_key(value):
    return type(value), value


data = {
    make_key(True): "boolean",
    make_key(1): "integer",
    make_key(1.0): "float"
}

print(data)

This way, they can be distinguished by type information.

However, whether this is necessary depends on business semantics; you should not blindly add complexity just to distinguish types.

9. Immutable Types and the Hashing Mechanism

Immutable objects are generally more suitable as dictionary keys and set elements.

Common immutable types include:

  • int
  • float
  • bool
  • str
  • bytes
  • tuple
  • frozenset

But it must be emphasized again: immutable does not necessarily mean hashable.

1. Integers and Strings

data = {
    1001: "Alice",
    "name": "Bob"
}

Both integers and strings can be used as dictionary keys.

2. Tuples as Composite Keys

locations = {
    (39.9042, 116.4074): "Beijing",
    (31.2304, 121.4737): "Shanghai"
}

Tuples can combine multiple values into one logical key.

For example:

  • Geographic coordinates.
  • Composite database primary keys.
  • Grid coordinates.
  • Multidimensional state indexes.

3. frozenset as a Key

permissions = {
    frozenset({"read", "write"}): "editor",
    frozenset({"read"}): "viewer"
}

frozenset is an immutable set, and when all its elements are hashable, it is itself hashable.

Therefore, it can be used as a dictionary key.

4. Choosing Between tuple and frozenset

Type Ordered? Allows Duplicates? Suitable Use Case
tuple Ordered Allowed Composite keys with a fixed structure
frozenset Unordered Automatically deduplicated Composite keys of unordered elements

If the order of the data is business-relevant, tuples should be preferred.

If you only care about the set relationship among elements and not their order, you can consider using frozenset.

10. Hash Randomization Mechanism

Python introduced hash randomization for types such as strings and byte strings.

Its purpose is to reduce the risk of attackers slowing down dictionary operations by constructing a large number of hash collisions.

1. Why Hash Randomization Is Needed

Suppose a web service receives data submitted by users and converts it into a dictionary.

If an attacker can construct a large number of string keys with hash collisions, it may significantly degrade dictionary operation performance.

This type of attack is commonly known as a hash flooding attack.

Hash randomization can make it harder for attackers to predict hash values and construct collisions.

2. String Hash Randomization in Python

You can observe:

print(hash("Python"))

When executed in different processes, it may produce different results.

The reason is that Python by default introduces a process-level random seed into hash computations for strings and byte strings.

3. The PYTHONHASHSEED Environment Variable

You can control hash randomization behavior via PYTHONHASHSEED.

For example:

PYTHONHASHSEED=0 python app.py

Or specify a fixed seed:

PYTHONHASHSEED=123 python app.py

Note the following:

  • PYTHONHASHSEED=0 disables hash randomization.
  • Specifying a nonzero integer uses a fixed seed.
  • If the variable is not set, the interpreter usually chooses a random seed.
  • This setting must take effect before the Python process starts.
  • Hash values are not guaranteed to be the same across different Python versions and implementations.

In production environments, you should not casually disable the randomization mechanism just to make hash values fixed.

4. Hash Randomization Is Not Encryption

Python's hash() is not a cryptographic hash function.

Do not use it to:

  • Store passwords.
  • Generate digital signatures.
  • Generate stable file digests.
  • Generate permanent business identifiers.
  • Verify data integrity.

If secure password storage is needed, use a dedicated password hashing algorithm with appropriate salt and parameter settings.

If you need file digests or content verification, consider cryptographic digest algorithms such as SHA-256.

11. Underlying Hash Table Implementation of Python Dictionaries

At an abstract level, a Python dictionary is a hash table.

In CPython, dictionaries use an optimized hash table structure to store key-value pairs.

Understanding its basic structure helps explain why dictionary lookups are usually fast.

1. Basic Components of a Hash Table

Conceptually, a hash table contains:

  • The hash value of a key.
  • The key object.
  • The corresponding value.
  • Internal structures used to locate entries and handle collisions.

Simplified illustration:

             Dictionary
                 |
                 v
          Hash Table Structure
                 |
         +-------+-------+
         |       |       |
         v       v       v
      Entry 1 Entry 2 Entry 3
         |       |       |
         v       v       v
    key/value key/value key/value

This is only a logical illustration and does not represent the actual memory layout of a CPython dictionary.

2. Hash Values and Storage Locations

A hash table needs to map hash values to internal storage locations.

Conceptually, this can be understood as:

index = f(hash(key), table\_size)

The actual CPython dictionary uses specialized index calculation and probing strategies, and is not simply equivalent to a fixed modulo operation.

3. The Compact Structure of CPython Dictionaries

Modern CPython dictionaries use a compact dictionary design, organizing index information and key-value entries internally.

This design reduces space overhead and supports efficient iteration.

From an implementation perspective:

  • The index structure helps locate candidate entries.
  • The entry structure stores keys and values.
  • Hash information is used to reduce unnecessary equality comparisons.
  • The probing mechanism is used to handle collisions.
  • The resizing mechanism is used to maintain a reasonable load factor.

The specific structure changes between CPython versions and is an implementation detail, not part of the Python language specification.

4. Open Addressing and Probing

CPython dictionaries use the idea of open addressing to handle hash collisions.

When the target location is already occupied by another key, the dictionary continues to search for a suitable location according to its probing strategy.

In simplified terms:

Compute hash value
    |
    v
Locate candidate position
    |
    v
Is the position occupied?
    |
    +---- No ----> Insert or search
    |
    +---- Yes ----> Check whether keys are equal
                      |
                      v
                If unequal, continue probing

In practice, CPython uses an optimized mechanism that combines hash values and probe sequences, so it should not be simply understood as linear probing.

5. Dictionary Resizing

As the number of elements in a dictionary gradually increases, the hash table needs to expand its capacity to avoid excessively high load levels affecting operation efficiency.

The resizing process typically involves:

  1. Allocating new internal storage space.
  2. Rearranging the index structure.
  3. Mapping existing key-value entries to the new hash table layout.
  4. Completing the switch to the new storage structure.

Therefore, dictionary insertion operations are fast on average, but individual insertions may require more work due to resizing.

12. Hashing Mechanism and Time Complexity of Dictionary Operations

The hashing mechanism allows dictionaries to perform lookups, insertions, and deletions quickly.

When the hash distribution is reasonable, common operations have the following average complexities: