summing values of dictionary "grouping by" keys-value in another dictionary

Viewed 50

I have a dictionary that looks like this

x = {'a': 2,
'b': 3,
'c': 3,
'd': 5,
'e': 4,
'f': 3,
'g': 5,
'h': 9}

while another dictionary that looks like this:

y = {'a': 'A',
    'b': 'B',
    'c': 'B',
    'd': 'B',
    'e': 'D',
    'f': 'C',
    'g': 'C',
    'h': 'D'}

what I want to do is to create a new dictionary that looks like this:

z = {'A': 2,
'B': 11,
'C': 8,
'D': 13}

so basically "group by" the elements in x according to the values in y and sum them. for instance, in y 'b','c','d', belong to 'B' so in z we will have B = 3+3+5 = 11,

3 Answers
z = {}
for k, v in y.items():
    z.setdefault(v, 0)
    z[v] += x[k]
print(z)

Prints:

{'A': 2, 'B': 11, 'D': 13, 'C': 8}

I think defaultdict can be a very readable solution:

from collections import defaultdict

z = defaultdict(int)
for k,v in y.items():
    z[v]+= x[k]

Similar to @Andrej solution but a little bit efficient.

Pythonic way:

z = {key: sum(x[elt] for elt,val in y.items() if val==key) for key in y.values()}

print(z)
# {'A': 2, 'B': 11, 'D': 13, 'C': 8}
Related