Dictionary keys that compare equal and have equal hashes refer to one mapping entry, even when their types differ.
Python interview: bool and int can address the same dictionary key
Operation contract
The permission flags are written with True and then 1 as keys. Since bool is an int subclass and these values compare equal with equal hashes, the second assignment replaces the first value rather than adding a second entry. The result has one key and its latest value. The lesson concerns key equality, not a claim that a boolean should be accepted as an integer identifier.
Failure and ownership boundary
At a data boundary, reject boolean IDs explicitly before storing them as integer keys. The same issue can affect set membership and deduplication. Python hash and equality: immutable dictionary keys, Python type conversion: parsing success is not field validity and Python interview: mutating a hash key breaks dictionary lookup assumptions cover the neighboring traps.
Working program
access = {True: "review"}
access[1] = "approve"
print("entries:", len(access))
print("by bool:", access[True])
print("by int:", access[1])
print("same hash:", hash(True) == hash(1))Output
entries: 1
by bool: approve
by int: approve
same hash: TrueCosts and limits
Both lookups are average constant-time mapping operations. A malicious or pathological key set can change collision costs, and no permission decision should be based on an unvalidated ID type.
Common Mistakes
- bool passes isinstance(value, int), so use a deliberate input rule.
- Distinct key types do not guarantee distinct dictionary entries.
Connected lessons
Python hash and equality: immutable dictionary keys, Python type conversion: parsing success is not field validity, Python interview: mutating a hash key breaks dictionary lookup assumptions.
