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}]
No voodoo is required, as long as you can guarantee b
has been populated with all the id
s 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With