简体   繁体   English

Python字典:排序问题

[英]Python Dictionary: Sorting Trouble

I thought i found away to sort a dictionary by clearing it then reassemble it in the order i wanted but for some reason it reorders itself the way it started out. 我以为我发现可以通过清除字典来对字典进行排序,然后按照我想要的顺序重新组装字典,但是由于某种原因,它会按照开始的方式对其进行重新排序。

Here is the code if somebody can help me out 如果有人可以帮助我,这是代码

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

字典本质上是无序的(因为它们使用哈希键-这是唯一的但任意的)[这是一个常见问题解答]-您可能要考虑使用OrderedDict (在2.7+版本中),它保留了插入顺序或PyPi的配方-否则,如果您需要订购,则需要按列表或其他顺序保留条目。

As Jon points out, dictionaries have no order. 正如乔恩(Jon)所指出的,字典没有顺序。 You get fast lookups by giving up ordering. 您可以通过放弃订购来快速查找。 You might not need it to keep an order though, since you have a sort order you like: 不过,由于您有自己喜欢的排序顺序,因此您可能不需要它来保持顺序:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM