← 中文资源

简体中文版本

True 与 1 在字典里撞键

True、1、1.0 相等且哈希一致,会占同一个字典键位、互相覆盖;键位显示首次插入的类型;来源类型需要区分时,先把键规范化成字符串再落库。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

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

实现说明

tallies、counts、safe 定义在模块顶层,中间不经过函数作用域。

使用要点

  • 每一步打印都带着自己的标签:tallies:、True == 1:、hash equal:。

常见问题

这份代码可以原样复制进项目使用吗?

可以。粘进去就能运行,中间没有包管理器的事。 文件用顶层绑定保存自己的状态:tallies、counts、safe。

核心语句

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 = {}

代码示例

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)