9

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"}
          ]
1
  • 1
    Note that the answers assume 'id' is some unique property among the objects. Commented Jul 16, 2023 at 15:08

4 Answers 4

11
object_map = {o['id']: o for o in objects}
objects = [object_map[id] for id in ids]
Sign up to request clarification or add additional context in comments.

1 Comment

I think I would factor the dict-comp out so you're not doing it over and over again.
2
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'}]

2 Comments

Strangely almost char for char what I had in my text editor ;)
@JonClements: We clearly spend far too much time on this site ;)
0
>>> 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']])

Comments

0

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.)

2 Comments

Ah yeah this is a much nicer answer.
Actually I take that back, this .index() gives this suboptimal complexity.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.