HussainNagri
HussainNagri

Reputation: 45

sort a dictionary within another dictionary

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

Answers (2)

mgilson
mgilson

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

eumiro
eumiro

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

Related Questions