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

fox*_*fox 1 python dictionary list python-2.7

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

for item in passedList:
    tempDict = {}
    tempDict ["first"] = item[0]
    tempDict ["second"] = item[1]
    tempDict ["third"] = item[2]
Run Code Online (Sandbox Code Playgroud)

我期待的是:

{'first': 'item1', 'second': 'item2', 'third': 'item3'}
Run Code Online (Sandbox Code Playgroud)

但是,我得到:

{'second': 'item2', 'first': 'item1', 'third': 'item3'}
Run Code Online (Sandbox Code Playgroud)

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

tim*_*imc 6

这是因为Python 中dict实现是一个hashmap或hash表,它不按顺序存储元素.

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