Suppose I have these lists:
ids = [4, 3, 7, 8]
objects = [
{"id": 7, "text": "are"},
{"id": 3, "text": "how"},
{"id": 8, "text": "you"},
{"id": 4, "text": "hello"}
]
How can I sort the objects
so the order of their ids matches ids
? I.e. to get this result:
objects = [
{"id": 4, "text": "hello"},
{"id": 3, "text": "how"},
{"id": 7, "text": "are"},
{"id": 8, "text": "you"}
]
Use the zip() and sorted() Functions to Sort the List Based on Another List in Python. In this method, we will use the zip() function to create a third object by combining the two given lists, the first which has to be sorted and the second on which the sorting depends.
Explained: zip the two list s. create a new, sorted list based on the zip using sorted() . using a list comprehension extract the first elements of each pair from the sorted, zipped list .
object_map = {o['id']: o for o in objects}
objects = [object_map[id] for id in ids]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With