A note when you want to sort the elements of a list in a specified order in Python.
I couldn't find a way to sort by another list by searching, so I wrote it. It can be used when you want to sort the response of external API or DB.
sort.py
from pprint import pprint
data_list = [
{"id": 1, "name": "aaa"},
{"id": 2, "name": "bbb"},
{"id": 3, "name": "ccc"},
{"id": 4, "name": "ddd"},
{"id": 5, "name": "eee"},
]
order = [
1,
5,
3,
2,
4
]
pprint(data_list)
print "-----"
pprint(sorted(data_list, key=lambda data: order.index(data["id"])))
result
[{'id': 1, 'name': 'aaa'},
{'id': 2, 'name': 'bbb'},
{'id': 3, 'name': 'ccc'},
{'id': 4, 'name': 'ddd'},
{'id': 5, 'name': 'eee'}]
-----
[{'id': 1, 'name': 'aaa'},
{'id': 5, 'name': 'eee'},
{'id': 3, 'name': 'ccc'},
{'id': 2, 'name': 'bbb'},
{'id': 4, 'name': 'ddd'}]
Recommended Posts