A lookup table retrieves a user by immutable numeric ID.
What You Need to Understand
Dictionaries and sets use hashing to locate keys or members efficiently on average. Hashability requires an object to have a suitable stable hash and consistent equality semantics during its use in a hash-based collection.
When to Use It
A lookup table retrieves a user by immutable numeric ID.
Step-by-Step Python Example
users = {101: "Maya", 102: "Noa"}
print(users.get(102))
ids = {101, 102}
print(103 in ids)
How the Example Works
Key lookup and set membership use hash-based structures rather than scanning positions as lists do.
Example Output
Noa
False
-3550055125485641917
True
A Second Example
Compare this smaller variation with the main example, then experiment with your own values.
print(hash((1, 2)))
print((1, 2) in {(1, 2)})
Important Behavior and Edge Cases
O(1) average behavior is not a guarantee for every operation or size. Never mutate the logical identity of an object while it is being used as a dictionary key.
Try It Yourself
Explain why a tuple of integers can be a key but a list cannot.
Common Beginner Mistakes
- O(1) average behavior is not a guarantee for every operation or size. Never mutate the logical identity of an object while it is being used as a dictionary key.
- Depending on set iteration order or using a set when duplicates and original positions must be preserved.
Key Takeaways
- Dictionaries and sets use hashing to locate keys or members efficiently on average.
- Key lookup and set membership use hash-based structures rather than scanning positions as lists do.
- O(1) average behavior is not a guarantee for every operation or size.