Sort list of dictionaries by another list.
I have got list with dictionaries (IN
) and I want to sort this by another list (sortValue
).
You can also use the key
parameter of the sorted
function. In your case, you want the index of sortValue for the id
of each item on the list:
>>> pprint(sorted(IN,key=lambda x:sortValue.index(x['id'])))
[{'id': 'b', 'val': 'Value', 'val1': 'Value1'},
{'id': 'c', 'val': 'Value', 'val1': 'Value1'},
{'id': 'a', 'val': 'Value', 'val1': 'Value1'}]
More on sorting with python on its wiki.