python - How to sort keys in dictionary if values are same ? -


sort dictionary score. if score same sort them name

import operator dt={  'sudha'  : {'score' : 75} , 'amruta' : {'score' : 95} , 'ramesh' : {'score' : 56} , 'shashi' : {'score' : 78} , 'manoj'  : {'score' : 69} , 'resham'  : {'score' : 95}  }   sorted_x1 = sorted(dt.items(), key=operator.itemgetter(1)) print sorted_x1 

output :

[('ramesh', {'score': 56}), ('manoj', {'score': 69}),   ('sudha', {'score':           75}),   ('shashi', {'score': 78}),   ('resham', {'score': 95}), ('amruta',{'score': 95})] 

now want sort last 2 elements name because scores same .

careful, code comparing dicts rather scores. ie

{'score': 56} < {'score': 69} 

may cause surprises if there keys in dictionaries. can arrange key func return tuple of score , key.

sorted_x1 = sorted(dt.items(), key=lambda (k, v): (v['score'], k)) 

if needs in python3, have avoid tuple unpacking in lambda no longer allowed.

sorted_x1 = sorted(dt.items(), key=lambda k_v: (k_v[1]['score'], k_v[0])) 

Comments

Popular posts from this blog

Android : Making Listview full screen -

javascript - Parse JSON from the body of the POST -

javascript - Chrome Extension: Interacting with iframe embedded within popup -