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.
Code
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
SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.bcrypt Cost EstimatorEstimate bcrypt cost factor latency and brute-force resistance, and get a recommended cost for your target hash time and attacker throughput.Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.SHA-256 Hash GeneratorGenerate SHA-256 cryptographic hashes from text input using the Web Crypto API. Compare hashes and verify data integrity with hexadecimal digest output.
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`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.