ZippyMind
ZippyMind

Reputation: 141

Sorting list of dictionaries using the values from another list of dictionaries

I got a list of dictionaries and want that to be sorted by a value from another dictionary.

This

[{'fld':'a1', 'sortkey':'k2'}, {'fld':'b1', 'sortkey':'k3'}, {'fld':'c1', 'sortkey':'k1'},{'fld':'d1', 'sortkey':'k3'}]

should use the following

[{'sortkey':'k1', 'value':9}, {'sortkey':'k2', 'value':10}, {'sortkey':'k3', 'value':7}]

and get to the following result

[ {'fld':'b1', 'sortkey':'k3'}, {'fld':'d1','sortkey':'k3'}, {'fld':'c1', 'sortkey':'k1'},{'fld':'a1', 'sortkey':'k2'} ]

Upvotes: 1

Views: 108

Answers (2)

Martijn Pieters
Martijn Pieters

Reputation: 1125258

You need to transform the second list into something you can actually use with any decent performance:

sort_map = {d['sortkey']: d['value'] for d in secondlist}

sorted(firstlist, key=lambda d: sort_map[d['sortkey']])

This presumes that for each sortkey value in firstlist there is a matching sortkey in the second.

This gives:

>>> firstlist = [{'fld':'a1', 'sortkey':'k2'}, {'fld':'b1', 'sortkey':'k3'}, {'fld':'c1', 'sortkey':'k1'},{'fld':'d1', 'sortkey':'k3'}]
>>> secondlist = [{'sortkey':'k1', 'value':9}, {'sortkey':'k2', 'value':10}, {'sortkey':'k3', 'value':7}]
>>> sort_map = {d['sortkey']: d['value'] for d in secondlist}
>>> sorted(firstlist, key=lambda d: sort_map[d['sortkey']])
[{'fld': 'b1', 'sortkey': 'k3'}, {'fld': 'd1', 'sortkey': 'k3'}, {'fld': 'c1', 'sortkey': 'k1'}, {'fld': 'a1', 'sortkey': 'k2'}]

Upvotes: 3

Andrew Clark
Andrew Clark

Reputation: 208715

Giving some names to your current lists:

data = [{'fld':'a1', 'sortkey':'k2'}, {'fld':'b1', 'sortkey':'k3'}, {'fld':'c1', 'sortkey':'k1'},{'fld':'d1', 'sortkey':'k3'}]
sorts = [{'sortkey':'k1', 'value':9}, {'sortkey':'k2', 'value':10}, {'sortkey':'k3', 'value':7}]

First I would convert sorts to the following:

{'k1': 9, 'k2': 10, 'k3': 7}

You can do this with the following code:

sorts_dict = {d['sortkey']: d['value'] for d in sorts}

Then you can get your final list using this:

result = sorted(data, key=lambda d: sorts_dict.get(d['sortkey']))

Upvotes: 2

Related Questions