【发布时间】:2016-05-15 18:32:13
【问题描述】:
有没有办法对多位数的字典值进行排序?我已经尝试过这里使用的方法:How to sort a dictionary to print from highest value to lowest for each key?,但它只适用于单个数字的整数值。例如,我的代码目前如下所示:
for line in students:
student = line.split(' ')
d[student[1]] = (student[3])
print (d)
od = sorted(d.items(), key=lambda x: x[1], reverse=True)
print(od)
students 是这个文本文件的 .readlines() 结果,我使用的是第一个分数:
Name= kirsty Score= 9 10 10 `
Name= anne Score= 4 5 6
Name= charlie Score= 1 1 1
Name= bruce Score= 7 8 9
Name= danny Score= 10 11 12
Danny 应该是字典中的第一个条目,但我的实际输出是这样的:
[('kirsty', '9'), ('bruce', '7'), ('anne', '4'), ('danny', '10'), ('charlie', '1')]
有人可以帮忙吗?
【问题讨论】:
-
试试
lambda x: int(x[1])作为排序键!
标签: python sorting dictionary