Reputation: 45
I want to Sort the dictionary by score. if the score is same then sort them by name
{
'sudha' : {score : 75}
'Amruta' : {score : 95}
'Ramesh' : {score : 56}
'Shashi' : {score : 78}
'Manoj' : {score : 69}
'Resham' : {score : 95}
}
Help plz Thanks.
Upvotes: 0
Views: 143
Reputation: 309929
I think this should work...
sorted(yourdict,key=lambda x:(yourdict[x]['score'],x))
It works by comparing tuples (score,name). Tuple comparison looks at the first item -- if those are the same, it looks at the second item and so forth. So, (55,'jack') > (54,'lemon) and (55,'j') < (55,'k').
Of course, this returns the keys of yourdict
in the order desired -- there's no way to actually sort a dictionary since dictionaries have no concept of order.
Upvotes: 6
Reputation: 212885
d = {
'sudha' : {'score' : 75},
'Amruta' : {'score' : 95},
'Ramesh' : {'score' : 56},
'Shashi' : {'score' : 78},
'Manoj' : {'score' : 69},
'Resham' : {'score' : 95},
}
sorted(d, key=lambda x: (d[x]['score'], x))
returns:
['Ramesh', 'Manoj', 'sudha', 'Shashi', 'Amruta', 'Resham']
Upvotes: 4