Reputation: 79
I have a list of dictionaries:
a = [{"id": 5, "data": "data1"}, {"id": 2, "data": "data2"}, {"id": 10, "data": "data3"}, {"id": 121, "data": "data4"}]
and a list of IDs:
ids_order = [10, 2, 5, 121]
I would like to reorder my list of dictionaries a
so that my new list new_a
have its dictionaries with value of the key "id" following the list ids_order
:
new_a = [{"id": 10, "data": "data3"}, {"id": 2, "data": "data2"}, {"id": 5, "data": "data1"}, {"id": 121, "data": "data4"}]
Is there an efficient way to do it with the sort function? So far I am making a double loop to get the correct element, which is not especially the best. However, I couldn't find anything that could match with the sort function.
Upvotes: 0
Views: 86
Reputation: 2162
ids_order = [10, 2, 5, 121]
int_order = [a[i]['id'] for i in range(4)]
ind_change = [int_order.index(ids_order[i]) for i in range(4)]
new_a = [a[i] for i in ind_change]
print(new_a)
Upvotes: 0
Reputation: 79
I solved the problem by making a nested comprehension list. It works, though I don't know if it's scalable with big lists.
new_a = [[feat for feat in a if feat["id"] == i][0] for i in ids_order]
Note: there's the [0]
to avoid a list of list.
Upvotes: 0
Reputation: 6234
you can make a temporary mapping temp
of ids to dictionary which can later be used to select according to the given order.
temp = {d["id"]: d for d in a}
new_a = [temp[i] for i in ids_order]
print(new_a)
Output:
[{'id': 10, 'data': 'data3'}, {'id': 2, 'data': 'data2'}, {'id': 5, 'data': 'data1'}, {'id': 121, 'data': 'data4'}]
Upvotes: 2