Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

sorting

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?

like image 866
Shreyans Avatar asked Feb 16 '23 21:02

Shreyans


1 Answers

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']))
like image 128
tamasgal Avatar answered Feb 18 '23 14:02

tamasgal