简体   繁体   中英

Sort list of dictionaries in Python according to another list

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.

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'}]
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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM