Sorting one list to match another in python

Question:

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"}
          ]
Asked By: Timmmm

||

Answers:

object_map = {o['id']: o for o in objects}
objects = [object_map[id] for id in ids]
Answered By: Pavel Anossov
In [25]: idmap = dict((id,pos) for pos,id in enumerate(ids))

In [26]: sorted(objects, key=lambda x:idmap[x['id']])
Out[26]: 
[{'id': 4, 'text': 'hello'},
 {'id': 3, 'text': 'how'},
 {'id': 7, 'text': 'are'},
 {'id': 8, 'text': 'you'}]
Answered By: NPE
>>> ids = [4,3,7,8]
>>> id_orders = {}
>>> for i,id in enumerate(ids):
...     id_orders[id] = i
... 
>>> id_orders
{8: 3, 3: 1, 4: 0, 7: 2}
>>> 
>>> sorted(objs, key=lambda x: id_orders[x['id']])
Answered By: Yarkee

Use sorted with a custom key function which simply gets index from ids:

sorted(objects, key=lambda x: ids.index(x['id']))

(Inspired by NPE’s answer.)

Answered By: Melebius
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.