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.
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.
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.
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.
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