【问题标题】:python iterating over dictionaries sorted by valuespython遍历按值排序的字典
【发布时间】:2014-10-30 09:34:08
【问题描述】:

下面的一段代码。谁能解释为什么迭代字典,最后一行,已经按值排序仍然输出字典不按值排序?当我尝试保存字典时同样适用。

#!/usr/bin/python

x = {1: 2999, 3: 4, 4: 3, 2: 1, 0: 0 }
srtkeys = sorted(x, key=x.get)
ds={}
print "\ncreating dict sorted by values"
for w in srtkeys:`enter code here`
        print w,x[w]
        ds[w] = x[w]

print "\nprinting dict sorted by values"
print ds

print "\niterating over dict sorted by values"
for k,v in ds.iteritems():
        print str(k)+":"+str(v)

输出:

creating dict sorted by values
0 0
2 1
4 3
3 4
1 2999

printing dict sorted by values
{0: 0, 1: 2999, 2: 1, 3: 4, 4: 3}

iterating over dict sorted by values
0:0
1:2999
2:1
3:4
4:3

【问题讨论】:

    标签: python sorting dictionary


    【解决方案1】:

    字典从不按定义排序。您可能想使用collections.OrderedDict

    【讨论】:

      【解决方案2】:

      字典没有内在的顺序,所以排序没有意义。如果您希望键:值对按特定顺序排列,只需遍历有序键列表,就像在您的第一个循环中一样。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-05-18
        • 2012-02-10
        • 2014-04-07
        • 2023-03-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多