Mayne Wong
Mayne Wong

Reputation: 81

Sort a list of dictionaries based on another list in Python

I have a list of dicts and a list like this:

dicts = [{"id": 1}, {"id": 4}, {"id": 7}, {"id": 0}]
ids = [7, 1, 0]

I want to dicts order by ids result like this:

[{"id": 7}, {"id": 1}, {"id": 0}]

Upvotes: 2

Views: 2064

Answers (3)

Subrata Sarkar
Subrata Sarkar

Reputation: 72

You cannot rearrange dictionaries as they are mapping type object in python so you can do one thing if you want the dict items to be printed in that order then you need to arrange the values in descending order by calling .values().

Upvotes: -1

Alex Hall
Alex Hall

Reputation: 36033

id_dict = {d['id']: d for d in dicts}
print([id_dict[i] for i in ids])

If ids might contain an id that isn't in any dict, just add a condition:

[id_dict[i] for i in ids if i in id_dict]

Upvotes: 7

Manu Valdés
Manu Valdés

Reputation: 2372

sorted(dicts, key = lambda item: ids.index(item['id']))

be aware this does not take into account if a particular id is in the ids list or not (with your data it would fail because 4is missing from the list).

Upvotes: 2

Related Questions