Skip to content Skip to sidebar Skip to footer

Python Sort A Json List By Two Key Values

I have a JSON list looks like this: [{ 'id': '1', 'score': '100' }, { 'id': '3', 'score': '89' }, { 'id': '1', 'score': '99' }, { 'id': '2', 'score': '100' }, { 'id': '2', 'score':

Solution 1:

use a tuple adding second sort key -int(k["score"]) to reverse the order when breaking ties and remove reverse=True:

sorted_list = sorted(json_list, key=lambda k: (int(k['id']),-int(k["score"])))

[{'score': '100', 'id': '1'}, 
 {'score': '99', 'id': '1'}, 
 {'score': '100', 'id': '2'}, 
 {'score': '59', 'id': '2'},
 {'score': '89', 'id': '3'}, 
 {'score': '22', 'id': '3'}]

So we primarily sort by id from lowest-highest but we break ties using score from highest-lowest. dicts are also unordered so there is no way to put id before score when you print without maybe using an OrderedDict.

Or use pprint:

from pprint import pprint as pp

pp(sorted_list)

[{'id': '1', 'score': '100'},
 {'id': '1', 'score': '99'},
 {'id': '2', 'score': '100'},
 {'id': '2', 'score': '59'},
 {'id': '3', 'score': '89'},
 {'id': '3', 'score': '22'}]

Post a Comment for "Python Sort A Json List By Two Key Values"