Skip to content
Advertisement

summing values of dictionary “grouping by” keys-value in another dictionary

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,

Advertisement

Answer

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}
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement