这是一种使用简单迭代的方法。
前任:
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