If value of one dictionary is the same as key of the second dictionary sum second dictionary values Python

Viewed 76

I want to sum the values of the second dictionary depending on the first dictionary. If I have dictionaries A and B.

A = {"Mark": ["a", "b", "c", "d"], "June": ["e", "a"], "John": ["a", "b", "f"]}
B = {"a": 1, "b": 2, "c": 3, "d": 0, "e": 3, "f": 2}

What the result should be is:

Mark=6, June = 4, John = 5

Thanks in advance

4 Answers

You can check if the values in list of first dictionary for a key is present as a key in the second dictionary and then you can use list comprehension and sum function to get the job done. Something similar to this:

A = {"Mark":["a", "b", "c", "d"], "June":["e", "a"], "John":["a", "b", "f"]}
B = {'a':1, 'b':2, 'c':3, 'd':0, 'e':3, 'f':2}
for k,v in A.items():
    total = sum([B[eachV] for eachV in v if eachV in B.keys()])
    print(f'{k}: {total}')
    
Mark: 6
June: 4
John: 5

UPDATE: Pointed by: @Mushif Ali Nawaz

If your data is going to be larger, you can consider using generator comprehension instead of list comprehension, for it is faster..

total = sum(B[eachV] for eachV in v if eachV in B.keys())

List comprehension changes to generator comprehension when square brackets are replaced by parenthesis.

You can do it like this:

for key, value in A.items():
    _sum = 0
    for val in value:
        _sum += B[val]
    print(key, '=', _sum)

Output:

Mark = 6
June = 4
John = 5

I found your question interesting, please review my answer if you found it beneficial.

A = {"Mark":["a", "b", "c", "d"], "June":["e", "a"], "John":["a", "b", "f"]}
B = {"a":1, "b":2, "c":3, "d":0, "e":3, "f":2}



result_list = []

for i in A.keys():
    result = 0
    for j in A.get(i):
        result = result + B.get(j)
    result_list.append(result)

print("final result  = ",dict(zip(A.keys(), result_list)))

Output:

final result  =  {'Mark': 6, 'June': 4, 'John': 5}

You can use a nested list comprehension:

A = {"Mark": ["a", "b", "c", "d"], "June": ["e", "a"], "John": ["a", "b", "f"]}
B = {"a": 1, "b": 2, "c": 3, "d": 0, "e": 3, "f": 2}
r = {a:sum(B[i] for i in b) for a, b in A.items()}
Related