Reputation: 4047
I have a list of dicts, where the dict has a list itself. How can I sort using factors index?
For example sort descending the list by factors[0]
[{'score': '2.0', 'id': 686, 'factors': [2.0, 2.25, 2.75, 1.5, 2.25]}, {'score': '1.9', 'id': 863, 'factors': [1.5, 3.0, 1.5, 2.5, 1.5]}, {'score': '2.0', 'id': 55, 'factors': [1.5, 3.0, 2.5, 1.5, 1.5]}, {'score': '1.9', 'id': 756, 'factors': [1.25, 2.25, 2.5, 2.0, 1.75]}]
Upvotes: 1
Views: 593
Reputation: 18367
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'}]
Upvotes: 1
Reputation: 8273
You can pass it as a key
my_list=[{'score': '2.0', 'id': 686, 'factors': [2.0, 2.25, 2.75, 1.5, 2.25]}, {'score': '1.9', 'id': 863, 'factors': [1.5, 3.0, 1.5, 2.5, 1.5]}, {'score': '2.0', 'id': 55, 'factors': [1.5, 3.0, 2.5, 1.5, 1.5]}, {'score': '1.9', 'id': 756, 'factors': [1.25, 2.25, 2.5, 2.0, 1.75]}]
sorted(my_list, key=lambda x: x['factors'][0])
Output:
[{'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]},
{'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]}]
Upvotes: 1