Sorting one list to match another in python

list, python, sorting

Solution

object_map = {o['id']: o for o in objects}
objects = [object_map[id] for id in ids]

Problem

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"} ] ```

Original source