简体   繁体   中英

how do I sort a python list of dictionaries given a list of ids with the desired order?

I've got a list of dictionaries like this:

users = [{'id':1, 'name': 'shreyans'}, {'id':2, 'name':'alex'}, {'id':3, 'name':'david'}]

and a list of ids with the desired order:

order = [3,1,2]

What's the best way to order the list users by the list order ?

users = [{'id':1, 'name': 'shreyans'},
         {'id':2, 'name':'alex'},
         {'id':3, 'name':'david'}]
order = [3,1,2]

users.sort(key=lambda x: order.index(x['id']))

If the lists are really big:

userd = {d['id']:d for d in users}
sortedusers = [userd.get(o) for o in order]

This is O(2n) . A solution using sort only will be O(n^3.log(n)) (sort is nlogn , finding position of every id in list is O(n^2) ), which is clearly worse for larger lists. For smaller lists (such as 3 items), the low overhead of not creating a new data structure will make it faster; conversely if you keep sorting by new order specifications, the overhead of making the new dict will quickly amortise.

使用自定义键排序:

users.sort(key=lambda x: order.index(x['id']))

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