【发布时间】:2012-07-11 00:38:10
【问题描述】:
我以为我是通过清除字典来对字典进行排序,然后按照我想要的顺序重新组装它,但由于某种原因,它会按照开始的方式重新排序。
如果有人可以帮助我,这是代码
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
【问题讨论】:
-
请注意,由于字符串是“按字母顺序”排序的,因此 '1'
-
另外,请避免使用 l 作为名称,请参见此处:python.org/dev/peps/pep-0008/#names-to-avoid
标签: python list sorting dictionary