Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort a list of dictionary provided an order

I've a list

order = [8, 7, 5, 9, 10, 11]

and a list of dictionaries

list_of_dct = [{'value':11}, {'value':8}, {'value':5}, {'value':7}, {'value':10}, {'value':9}]

I want to sort this list_of_dct by the order given in order list, i.e. the output should be the following:

list_of_dct = [{'value':8}, {'value':7}, {'value':5}, {'value':9}, {'value':10}, {'value':11}]

I know how to sort by a given key, but not when an order is already given. How can I sort it?

PS: I already have an O(n^2) solution. Looking for a better solution.

like image 273
PythonEnthusiast Avatar asked Jan 29 '16 06:01

PythonEnthusiast


People also ask

Can you sort a list of dictionaries?

To sort a list of dictionaries according to the value of the specific key, specify the key parameter of the sort() method or the sorted() function. By specifying a function to be applied to each element of the list, it is sorted according to the result of that function.

Can we sort list of dictionary in Python?

We can sort lists, tuples, strings, and other iterable objects in python since they are all ordered objects. Well, as of python 3.7, dictionaries remember the order of items inserted as well. Thus we are also able to sort dictionaries using python's built-in sorted() function.


1 Answers

Use index of the order list to sort-Just try if every dictionary has one value and you want sorting by that value-

sorted(list_of_dct,key=lambda x:order.index(x.values()[0]))

But if you have multiple values for one key then change the index (i.e [0]) on which you will sort.

like image 109
SIslam Avatar answered Oct 07 '22 10:10

SIslam