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

python, sorting

Solution

Use sort with a custom key:

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

Problem

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`?

Original source