Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting one list to match another in python

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"}
          ]
like image 277
Timmmm Avatar asked Apr 08 '13 13:04

Timmmm


People also ask

How do you sort one list by another list in Python?

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.

How do you sort a list on basis of another list?

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 .


1 Answers

object_map = {o['id']: o for o in objects}
objects = [object_map[id] for id in ids]
like image 103
Pavel Anossov Avatar answered Sep 25 '22 15:09

Pavel Anossov