【问题标题】:strange dictionary iteration order [duplicate]奇怪的字典迭代顺序[重复]
【发布时间】:2012-11-13 12:42:05
【问题描述】:

可能重复:
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'}

【问题讨论】:

  • 因为字典不是序列。它没有订单。
  • 如果你真的想使用这个字典并打印它排序,你也可以使用:print "{%s}" % (", ".join(["'%s': '%s'" % (k,v) for (k,v) in sorted(newDict.iteritems(),key=itemgetter(0))]))。顺便说一句,你也可以用newDict = dict([(k,k in moon and moon[k] or v) for (k,v) in lunar.iteritems()])构造newDict

标签: python dictionary


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    Python dict 未排序。出于性能原因,忘记添加项目的顺序对实现来说效率更高。

    作为documentation states

    键和值以非随机的任意顺序列出,因 Python 实现而异,并且取决于字典的插入和删除历史。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-25
      • 2019-02-14
      • 2013-11-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多