Python词典:排序麻烦

时间:2012-07-11 00:38:10

标签: python list sorting dictionary

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

以下是有人可以帮助我的代码

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

2 个答案:

答案 0 :(得分:10)

词典本质上是无序的(因为它们使用哈希键 - 这是唯一的但是是仲裁的)[这是常见问题解答] - 您可能要考虑使用保留插入顺序的OrderedDict(在2.7+中)或来自PyPi的食谱 - 否则,如果您需要订单,则需要将条目保留在列表或其他序列中。

答案 1 :(得分:4)

Jon指出,词典没有顺序。通过放弃订购,您可以快速查找。您可能不需要它来保留订单,因为您有一个您喜欢的排序顺序:

d = {'a':['2', 'ova', 'no'], 'b':['23', 'movie', 'yes'], 'c':['5', 'show', 'yes'], 'd':['17', 'ova', 'yes'], 'e':['1', 'movie', 'no']}
sorted_items = sorted(d.items(), key=itemgetter(1))
for i,v in sorted_items:
    print i, v