首页 > 解决方案 > 按字典python列表中的值总和排序

问题描述

我有一本这样的字典:

d = {'a':[{'a1':1},{'a2':5},{'a3':4}], 'b':[{'b1':0},{'b2':1},{'b3':2}], 'c':[{'c1':1},{'c2':2}]}

我想按每个中的值的总和list(字典中每个项目的值)对其进行排序,以便得到:

r = [('a', (10, [{'a1':1},{'a2':5},{'a3':4}])),
('b', (3, [{'b1':0},{'b2':1},{'b3':2}])),# 'b' and 'c' have sum of '3', so they tied here
('c', (3, [{'c1':1},{'c2':2}]))]

我可以用一种天真的方法来完成这项工作。我想知道如何以更 Pythonic 的方式完成此任务。我已经尝试过了,但由于明显的原因没有奏效:

sorted(sum(d.values()), key=d.get, reverse=True)

预先感谢您的回答!

标签: pythondictionarylist-comprehension

解决方案


你可以试试这个:

d = {'a':[{'a1':1},{'a2':5},{'a3':4}], 'b':[{'b1':0},{'b2':1},{'b3':2}], 'c':[{'c1':1},{'c2':2}]}
new_d = {a:(sum(list(i.values())[0] for i in b), b) for a, b in d.items()}
final_result = sorted(new_d.items(), key=lambda x:x[-1][0], reverse=True)

输出:

('a', (10, [{'a1': 1}, {'a2': 5}, {'a3': 4}])), ('c', (3, [{'c1': 1}, {'c2': 2}])), ('b', (3, [{'b1': 0}, {'b2': 1}, {'b3': 2}]))]

推荐阅读