Py学习  »  Python

python:按字典中的特定键和这些键值的总和分组

user8195447 • 5 年前 • 1462 次点击  
dict_ot={"Berlin":4, "London":3,"Madrid":3,"Germany":51, "Others":1, "France":4}

在上面的字典中,我希望有下面的输出,在 = 符号:

Berlin, Germany = 55
Madrid, Others = 4
London =7

我会用它做条形图…

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/38545
 
1462 次点击  
文章 [ 1 ]  |  最新文章 5 年前
Rakesh
Reply   •   1 楼
Rakesh    6 年前

这是一种使用简单迭代的方法。

前任:

from collections import defaultdict
dict_ot={"Berlin":4, "London":3,"Madrid":3,"Germany":51, "Others":1, "France":4}
grpBy = [("Germany", "Berlin"), ("Madrid", "Others"), ("London",)]
res = defaultdict(int)
for i in grpBy:
    for j in i:
        res[i] += dict_ot[j]

for k, v in res.items():
    print("{}: {}".format(", ".join(k), v))

输出:

Germany, Berlin: 55
London: 3
Madrid, Others: 4