True And One Collide As Dict Keys

True, 1, and 1.0 compare equal and hash equal, so they occupy one dict slot; normalize keys to strings when the source type has to stay distinguishable.

PythonData Integrity

Code

pythonsnippet
19 lines
tallies = {}

# True equals 1 and hashes identically, so both occupy one key slot; the later write wins
tallies[True] = "bool entry"
tallies[1] = "int entry"
print("tallies:", tallies)
print("True == 1:", True == 1)
print("hash equal:", hash(True) == hash(1))

# 1.0 maps to the same key slot as well
counts = {1: "one"}
counts[1.0] = "float one"
counts[True] = "flag"
print("counts:", counts)

# when the source type matters, normalize keys to strings first
safe = {"true": [], "1": []}
safe["true"].append("x")
print("safe:", safe)

Output

Captured from a sandboxed run of this snippet in the build pipeline.

tallies: {True: 'int entry'}
True == 1: True
hash equal: True
counts: {1: 'flag'}
safe: {'true': ['x'], '1': []}

How it works

Each step operates on the top-level bindings: tallies, counts, safe.

What to watch for

  • Runs on the standard library alone; nothing to install.

Using it

Output lines are prefixed (tallies:, True == 1:, hash equal:), so every step’s effect is easy to pick out.

Key statements

tallies[True] = "bool entry"
tallies[1] = "int entry"
print("tallies:", tallies)
print("True == 1:", True == 1)
print("hash equal:", hash(True) == hash(1))
# 1.0 maps to the same key slot as well
counts = {1: "one"}
safe = {"true": [], "1": []}
tallies = {}

Interactive Tools for This Topic

FAQ

Can I paste this into a project as-is?
Yes. Paste it in and run; no package manager step is needed. Its state lives in module-level bindings: `tallies`, `counts`, `safe`.