Sort dict by second value in tuple and return dict

时间:2015-10-30 21:35:19

标签: sorting python-3.x dictionary defaultdict

from collections import defaultdict,OrderedDict
tt=defaultdict (list)

tt={'abcd':(23,77),'ddef':(55,22)}

c=OrderedDict (sorted (tt.items (),key=lambda t: t[1][1]))

print (c)
d=list ((k,v) for k,v in c.items())

print (d)

This sorts correctly for c.
List makes the dict from the OrderedDict

d gets {'ddef':(55,22),'abcd':(23,77)}

1 个答案:

答案 0 :(得分:0)

修改了代码。现在工作正常。
我需要通过元组的第二个元素按排序顺序显示top(n)键 Dict似乎是最好的路线,列表中只有50个项目,我需要排在前十位。