Search code examples
sortingpython-3.xdictionarydefaultdict

Sort dict by second value in tuple and return dict


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)}


Solution

  • Modified the code. Works fine now.
    I need to display top (n) keys in a sorted order by the second element of the tuple.
    Dict seems to be the best route, there are only ever 50 items in the list,I need the top ten in order.