奇怪的字典迭代顺序

时间:2012-11-13 12:42:06

标签: python dictionary

  

可能重复:
  Why is python ordering my dictionary like so?

我有这个完全正常工作的代码,但它的行为很奇怪:字典中的项目不是按顺序迭代,而是以某种方式随机迭代,为什么会这样?:

#!/usr/bin/python

newDict = {}
lunar = {'a':'0','b':'0','c':'0','d':'0','e':'0','f':'0'}
moon = {'a':'1','d':'1','c':'1'}

for il, jl in lunar.items():
    print "lunar: " + il + "." + jl 
    for im, jm in moon.items():
        if il == im:
            newDict[il] = jm
            break
        else:
            newDict[il] = jl

print newDict

输出:

lunar: a.0
lunar: c.0
lunar: b.0
lunar: e.0  
lunar: d.0
lunar: f.0
{'a': '1', 'c': '1', 'b': '0', 'e': '0', 'd': '1', 'f': '0'}

2 个答案:

答案 0 :(得分:5)

字典不保存输入顺序。您可以在集合模块中尝试OrderedDict类 - OrderedDict Examples and Recipes

答案 1 :(得分:3)

Python dict未订购。出于性能原因,实施会更有效地忘记添加项目的顺序。

作为documentation states

  

键和值以任意顺序列出,这是非随机的,在Python实现中各不相同,并且取决于字典的插入和删除历史。

如果您需要有序字典,可以使用OrderedDict

相关问题