此问题已在此处有答案:
How come I can add the boolean value False but not True in a set in Python? [duplicate](3个答案)
Is False == 0 and True == 1 an implementation detail or is it guaranteed by the language?(4个答案)
昨天关门了。
这篇文章是昨天编辑并提交审查的。
我正在用Python编写一个关于字典的简单例子,我意识到有一个问题,我不理解它。
paris = {
1: 'apple',
'orange': [2, 3, 4],
True: False,
12: 'True',
}
print(paris)
为什么这段代码的输出是:{1: False, 'orange': [2, 3, 4], 12: 'True'}
而不是{1: 'apple', 'orange': [2, 3, 4], True:False, 12: 'True'}
键1
的值是False
,而不是我预期的'apple'
。如果我对键1使用另一个数字,我会得到预期的输出。
2条答案
按热度按时间qnakjoqk1#
这个错误是因为你同时拥有键1和True,后者解析为1。由于在Python字典中,键必须是唯一的,因此
1:apple
被True: False
覆盖,显示为1: False
。将布尔值和其他类型的变量沿着放入字典中并不是一个好主意。
fumotvh32#
有两件事需要理解:
1.在Python中,boolean数据类型是int数据类型的子类。这意味着True是1,False是0。所以,True被转换为1。
1.在Python中,字典中的键必须是唯一的。因此,当您为同一个键分配一个对应的值时(如True现在为1),它将更新dictionary的值。
所以数据:1:'apple'和True:False将导致1:False