Python字典:排序Troub

2024-09-28 15:36:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我想我找到了一个方法,通过清理一本字典,然后按照我想要的顺序重新组合它,但由于某些原因,它重新排列了它最初的样子。在

如果有人能帮我的话,这是密码

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

Tags: the方法noinfromfor字典顺序
2条回答

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

正如乔恩指出的,字典没有顺序。你可以通过放弃订购来快速查找。但是,您可能不需要它来保持顺序,因为您有一个您喜欢的排序顺序:

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

相关问题 更多 >