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

时间:2018-08-26 00:21:13

标签: python python-3.x dictionary pandas-groupby

dict_ot={"Berlin":4, "London":3,"Madrid":3,"Germany":51, "Others":1, "France":4}

在上面的词典中,我想获得以下输出,将每个=之后的总数与总数相加:

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

我将其用于条形图...

1 个答案:

答案 0 :(得分:0)

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

例如:

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