Outcast
Outcast

Reputation: 5117

Sort list of dicts according to another one

I have these two lists of dicts:

list_1 = [{'document_id': '5'}, {'document_id': '2'}, {'document_id': '4'}]

list_2 = [{'document_id': '4', 'page_id': '1'}, {'document_id': '5', 'page_id': '2'}, {'document_id': '5', 'page_id': '1'}]

list_1 is a superset of list_2 in terms of the document_id if this helps.

I want to

  1. sort list_2 according to list_1
  2. then sort list_2 based on the page_id for each distinct document_id

Therefore, I want to finally have this:

new_list_2 = [{'document_id': '5', 'page_id': '1'}, {'document_id': '5', 'page_id': '2'}, {'document_id': '4', 'page_id': '1'}]

How can I efficiently do this?

Upvotes: 1

Views: 33

Answers (2)

Alexander
Alexander

Reputation: 109746

Create a mapping of the ordering in list_1 via a dictionary comprehension.

docs = {doc.get('document_id'): n for n, doc in enumerate(list_1)}
# >>> docs
# {'5': 0, '2': 1, '4': 2}

Then use the ordering with the page_id as the sort keys.

list_2.sort(key=lambda r: (docs[r['document_id']], r['page_id']))

>>> list_2
[{'document_id': '5', 'page_id': '1'},
 {'document_id': '5', 'page_id': '2'},
 {'document_id': '4', 'page_id': '1'}]

Upvotes: 2

wjandrea
wjandrea

Reputation: 33179

  1. This is basically the same as How to sort a list according to another list? The only difference is you need to get the document ID's from list_1 first.
  2. See Sort a list by multiple attributes?

All together:

docs_1 = [d['document_id'] for d in list_1]  # = ['5', '2', '4']
list_2.sort(key=lambda d: (docs_1.index(d['document_id']), d['page_id']))

Upvotes: 0

Related Questions