Praful Bagai
Praful Bagai

Reputation: 17382

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.

Upvotes: 5

Views: 111

Answers (2)

Learner
Learner

Reputation: 5292

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.

Upvotes: 5

falsetru
falsetru

Reputation: 369054

Make a mapping of 8 to 0, 7 to 1, ..., 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 in case of value is misisng in order.

Upvotes: 3

Related Questions