2014-10-30 196 views
-3

下面的一段代码。任何人都可以解释为什么迭代字典,最后一行,已经按值排序仍输出字典不按值排序?当我尝试保存字典时,情况也是如此。Python遍历按值排序的字典

#!/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 

回答

0

的字典没有内在的顺序,因此排序没有任何意义。如果你想按照特定的顺序输入关键字:值对,就像在第一个循环中一样,遍历有序键列表。