【问题标题】:object not forming correctly when I create a dict object当我创建一个 dict 对象时,对象没有正确形成
【发布时间】:2013-01-14 00:50:12
【问题描述】:

我有一个 Python 函数的一部分,看起来像:

for item in passedList:
    tempDict = {}
    tempDict ["first"] = item[0]
    tempDict ["second"] = item[1]
    tempDict ["third"] = item[2]

我期待的是:

{'first': 'item1', 'second': 'item2', 'third': 'item3'}

但是,我得到:

{'second': 'item2', 'first': 'item1', 'third': 'item3'}

这可能是一个非常简单的疏忽,但有什么想法会发生这种情况吗?

【问题讨论】:

    标签: python list dictionary python-2.7


    【解决方案1】:

    这是因为 Python 中的implementation of dict 是一个 hashmap 或 hash table,它不会按顺序存储元素。

    您可以使用OrderedDict 来解决这个问题。

    【讨论】:

    • OrderedDict 会按字母顺序排列“第一”、“第二”、“第三”吗?
    • @Fox:根据答案中的链接:“OrderedDict 是一个 dict,它记住了第一次插入键的顺序”
    • 不,没有“排序”。它将记住输入密钥的顺序,并每次以相同的顺序返回它们。当您专门设置“第一”然后“第二”然后“第三”时,它将保留此顺序。
    猜你喜欢
    • 2019-09-09
    • 2020-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-07
    • 2017-10-05
    • 1970-01-01
    相关资源
    最近更新 更多