在创建dict对象时,对象形成不正确

时间:2013-01-14 00:50:13

标签: python list dictionary python-2.7

我有一个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'}

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

1 个答案:

答案 0 :(得分:6)

这是因为Python中的implementation of dict是一个散列图或散列表,它不按顺序存储元素。

您可以使用OrderedDict解决此问题。