Reputation: 5117
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
list_2
according to list_1
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
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
Reputation: 33179
list_1
first.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