python - 按字典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)
预先感谢您的回答!
解决方案
你可以试试这个:
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}]))]
推荐阅读
- saml - Okta 作为 SP(入站 SAML)如何在成功登录后配置重定向 URL
- applescript - mac 上的 Spotify 流甲板插件缺少重复切换
- android - Unity - Android - BLE 蓝牙权限
- c# - 在 C# 中结合动态绑定和非托管约束
- javascript - 必须表达包含两个逻辑运算符(|| 和 &&)的复杂条件的 switch 语句看起来如何?
- python - 我想通过麦克风发送我正在计算机上收听的音频
- mysql - 如何将“当前”mysql时间戳值迁移到postgreSQL
- linux - GNU 并行 - 通过多个 ssh 跳转主机运行命令
- c - 当应用于无符号操作数和有符号操作数时,整数除法会产生不同的结果吗?
- c# - C# 使用 count 属性反序列化对象的最佳方法