Thursday, December 3, 2026 | London 10°C · Drizzle
DailyGlimpse

AI

Python Quirks: Why True and 1 Can Overwrite the Same Dictionary Key

DEVLORE 1 min read

A recent Python short explains a subtle behavior in dictionary lookups: keys with the same hash, such as True and 1, are considered identical. This means that if you assign a value to the key 1 and later assign another value to the key True, the original value under 1 is overwritten.

Python dictionaries rely on hash tables for fast lookups, but when two distinct objects produce the same hash, Python uses an equality check to determine if they are the same key. Since True and 1 share the same hash and are equal in Python, they collide. This can lead to unexpected behavior for developers who assume True and 1 are separate dictionary keys.

The takeaway: when using booleans or integers as dictionary keys, remember their hash equivalence to avoid silent overwrites.

React