How to sort a list of dictionaries in python with a list of identifiers in the correct order?

I have a list of such dictionaries:

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

and a list of identifiers with the required order:

 order = [3,1,2] 

What is the best way to order the users list from the order list?

+4
source share
3 answers

Use sorting with a custom key:

 users.sort(key=lambda x: order.index(x['id'])) 
+2
source
 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'])) 
+3
source

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 only sort would be O(n^3.log(n)) (sort nlogn , with a search for each identifier in the list equal to O(n^2) ), which is clearly worse for large lists. For smaller lists (for example, 3 items), the low overhead of not creating a new data structure will make it faster; conversely, if you continue sorting by the new order specifications, the overhead of creating a new dict is quickly amortized.

+3
source

Source: https://habr.com/ru/post/1492177/


All Articles