Sorting the dictionary list when ordering

I have 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 in the order specified in the order list, i.e. The result should be as follows:

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

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

PS: I already have an O (n ^ 2) solution. Search for the best solution.

+5
source share
2 answers

Use the order index to sort. Just try if each dictionary has one value and you want to sort it by that value -

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

But if you have several values ​​for one key, change the index (ie [0] ) by which you will sort.

+5
source

Make a mapping from 8 to 0, from 7 to 1, ..., from 11 to 5, using enumerate :

 >>> order = [8,7,5,9,10,11] >>> list_of_dct = [{'value':11}, {'value':8}, {'value':5}, {'value':7}, {'value':10}, {'value':9}] >>> sort_keys = {item: i for i, item in enumerate(order)} >>> sort_keys {5: 2, 7: 1, 8: 0, 9: 3, 10: 4, 11: 5} 

And use it as a sorting key:

 >>> list_of_dct.sort(key=lambda d: sort_keys.get(d['value'], len(sort_keys))) >>> list_of_dct [{'value': 8}, {'value': 7}, {'value': 5}, {'value': 9}, {'value': 10}, {'value': 11}] 

use sort_keys.get(..) instead of sort_keys[..] to prevent KeyError if the value is misisng in order .

+3
source

Source: https://habr.com/ru/post/1241778/


All Articles