[英]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'} ]
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. 假定对于第一列表中的每个
sortkey
值,第二个firstlist
都有一个匹配的sortkey
。
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'}]
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: 首先,我将
sorts
转换为以下内容:
{'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']))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.