I have a dictionary that looks like this
JavaScript
x
9
1
x = {'a': 2,
2
'b': 3,
3
'c': 3,
4
'd': 5,
5
'e': 4,
6
'f': 3,
7
'g': 5,
8
'h': 9}
9
while another dictionary that looks like this:
JavaScript
1
9
1
y = {'a': 'A',
2
'b': 'B',
3
'c': 'B',
4
'd': 'B',
5
'e': 'D',
6
'f': 'C',
7
'g': 'C',
8
'h': 'D'}
9
what I want to do is to create a new dictionary that looks like this:
JavaScript
1
5
1
z = {'A': 2,
2
'B': 11,
3
'C': 8,
4
'D': 13}
5
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
JavaScript
1
6
1
z = {}
2
for k, v in y.items():
3
z.setdefault(v, 0)
4
z[v] += x[k]
5
print(z)
6
Prints:
JavaScript
1
2
1
{'A': 2, 'B': 11, 'D': 13, 'C': 8}
2