Reputation: 81
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
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
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
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 4
is missing from the list).
Upvotes: 2