Essentially what you need to do is use sorted
. However this factors[0]
seems a bit arbitrary, perhaps you want to sort the list first and then sort by its first value?
However this exmple get the jobs done. Keep in mind it won't be usable for ties, so you might want to add a second sorting key:
sort = sorted(ex, key=lambda x: x['factors'][0])
sort
Output:
[{'factors': [1.25, 2.25, 2.5, 2.0, 1.75], 'id': 756, 'score': '1.9'},
{'factors': [1.5, 3.0, 1.5, 2.5, 1.5], 'id': 863, 'score': '1.9'}, #Tied values
{'factors': [1.5, 3.0, 2.5, 1.5, 1.5], 'id': 55, 'score': '2.0'}, #Tied values
{'factors': [2.0, 2.25, 2.75, 1.5, 2.25], 'id': 686, 'score': '2.0'}]
Example of sorting by factors[0]
followed by id
for tied values. Please note how the order is the other way around, first you sort by id (inner sort) and then factors in the code (outer sort):
sort = sorted(sorted(ex,key=lambda x: x['id']),key=lambda x: x['factors'][0])
sort
Output:
[{'factors': [1.25, 2.25, 2.5, 2.0, 1.75], 'id': 756, 'score': '1.9'},
{'factors': [1.5, 3.0, 2.5, 1.5, 1.5], 'id': 55, 'score': '2.0'},
{'factors': [1.5, 3.0, 1.5, 2.5, 1.5], 'id': 863, 'score': '1.9'},
{'factors': [2.0, 2.25, 2.75, 1.5, 2.25], 'id': 686, 'score': '2.0'}]