Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python, sort a list of dicts by an arbitrary order [duplicate]

Tags:

python

Possible Duplicate:
Sorting list of lists by a third list of specified non-sorted order

a = [{'id':1}, {'id':2}, {'id':3}]
b = [2,1,3]

What would be a good method to sort dict a by list b via the id property.

The result should look something like this

[{'id':2}, {'id':1}, {'id':3}]
like image 404
Matt Avatar asked Dec 20 '22 22:12

Matt


1 Answers

No voodoo is required, as long as you can guarantee b has been populated with all the ids in a:

In [1]: a = [{'id':1}, {'id':2}, {'id':3}]

In [2]: b = [2,1,3]

In [3]: a.sort(key=lambda v : b.index(v['id']))

In [4]: a
Out[4]: [{'id': 2}, {'id': 1}, {'id': 3}]

(I'm often told there's an alternative to lambda that should be used nowadays, but this is still the clearest way I know for doing this)

EDIT: Also note that this is nearly identical to this answer in the linked question.

like image 127
Izkata Avatar answered Dec 23 '22 12:12

Izkata