You can sort by a tuple:
sorted(l, key=lambda k: (float(k['score']), k['id']), reverse=True)
This will sort by score
descending, then id
descending. Note that since score
is a string value, it needs to be converted to float
for comparison.
[
{'score': '2.0', 'id': 686, 'factors': [2.0, 2.25, 2.75, 1.5, 2.25]},
{'score': '2.0', 'id': 55, 'factors': [1.5, 3.0, 2.5, 1.5, 1.5]},
{'score': '1.9', 'id': 863, 'factors': [1.5, 3.0, 1.5, 2.5, 1.5]},
{'score': '1.9', 'id': 756, 'factors': [1.25, 2.25, 2.5, 2.0, 1.75]}
]
To sort by id
ascending, use -k['id']
(sorting negated numbers descending is equivalent to sorting the non-negated numbers ascending):
sorted(l, key=lambda k: (float(k['score']), -k['id']), reverse=True)
[
{'score': '2.0', 'id': 55, 'factors': [1.5, 3.0, 2.5, 1.5, 1.5]},
{'score': '2.0', 'id': 686, 'factors': [2.0, 2.25, 2.75, 1.5, 2.25]},
{'score': '1.9', 'id': 756, 'factors': [1.25, 2.25, 2.5, 2.0, 1.75]},
{'score': '1.9', 'id': 863, 'factors': [1.5, 3.0, 1.5, 2.5, 1.5]}
]