Python字典没有分配的所有键或项目 [英] Python dictionary doesn't have all the keys assigned, or items
本文介绍了Python字典没有分配的所有键或项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我创建了以下字典
exDict = {True: 0, False: 1, 1: 'a', 2: 'b'}
当我打印 exDict.keys()
,那么它给了我一个生成器。好的,所以我强迫它列表,它给了我
and when I print exDict.keys()
, well, it gives me a generator. Ok, so I coerce it to a list, and it gives me
[False, True, 2]
为什么不是1?当我打印 exDict.items()
它给我
Why isn't 1 there? When I print exDict.items()
it gives me
[(False, 1), (True, 'a'), (2, 'b')]
任何人都猜测这里发生了什么?我被困了。
Anyone have a guess about what's going on here? I'm stumped.
推荐答案
这是因为 True == 1
(和 False == 0
,但您没有将 0
作为键)。你必须以某种方式重构你的代码或数据,因为一个 dict
认为如果它们是相等的,则键是相同的(而不是
)。
This happens because True == 1
(and False == 0
, but you didn't have 0
as a key). You'll have to refactor your code or data somehow, because a dict
considers keys to be the same if they are "equal" (rather than is
).
这篇关于Python字典没有分配的所有键或项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文