Python词典:排序麻烦

Cri*_*spy 0 python sorting dictionary list

我以为我发现要通过清除它来排序字典,然后按照我想要的顺序重新组装它,但由于某种原因它按照它开始的方式重新排序.

这是代码,如果有人可以帮助我

from operator import itemgetter

n = {}
d = {
 'a': ['2', 'ova', 'no'], 
 'b': ['23', 'movie', 'yes'], 
 'c': ['5', 'show', 'yes'], 
 'd': ['17', 'ova', 'yes'], 
 'e': ['1', 'movie', 'no']
}

for i in d:
    print i, d[i]

print '\n'

l = d.items()
l.sort(key=itemgetter(1)) #l is now sorted by the value of the string holding the integers
d.clear()

for i in l:
    print i[0], i[1]
    d[i[0]] = i[1] 

print '\n'

for i in d:
    print i, d[i] #Why does the dictionary come out to be the same it started from
Run Code Online (Sandbox Code Playgroud)

Jon*_*nts 10

字典本身未排序(因为它们使用哈希键-这是唯一的,但arbitary)这是一个常见问题] -你可能要考虑使用OrderedDict它保留广告订单或一封来自PyPI配方(以2.7+) -否则,如果您需要订单,则需要将条目保留在列表或其他顺序中.