python - 按字典 python 列表中值的总和排序

标签 python dictionary list-comprehension

我有一本这样的字典:

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

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

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}]))]

关于python - 按字典 python 列表中值的总和排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50954906/

相关文章:

python - 如何根据列映射减去两个数据帧?

python - if else 使用 python 列表推导嵌套 for 循环

python - 字典列表中的字典

javascript - 为什么 JS hash/dict 中的 "key"部分应该是一个字符串?

python - 使用 lambda 的列表理解中的 If 语句

Python条件字典理解

python - 无法使用 OpenCV 创建基本视频文件

python - 文字识别。字符分割阶段

python - 在python中格式化输出

c++ - 在 map<char, int> 中发布查找值