我有一本这样的字典:
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}]))]
我可以天真地做到这一点。我想知道如何以更Python化的方式完成此任务。我已经尝试过,但是由于明显的原因而无法正常工作:
sorted(sum(d.values()), key=d.get, reverse=True)
预先感谢您的回答!
答案 0 :(得分:1)
您可以尝试以下方法:
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}]))]