Python – How to assign certain scores in a list to values in multiple lists and get the sum of each value in python?

How to assign certain scores in a list to values in multiple lists and get the sum of each value in python?… here is a solution to the problem.

How to assign certain scores in a list to values in multiple lists and get the sum of each value in python?

Can you explain how to assign certain scores from one list to values in multiple lists, and get the total score for each value?

score

= [1,2,3,4,5] assigns a score based on its position in the list

l_1 = [a,b,c,d,e]
Assignments a=1, b=2, c=3, d=4, e=5

l_2 = [c,a,d,e,b]
Assign c=1, a=2, d=3, e=4, b=5

I want to get such a result
{'e':9, 'b': 7, 'd':7, 'c': 4, 'a': 3}

Thanks!

Solution

You can zip the value of score to each list, which provides a tuple-fraction combination (key, value) for each letter. Make each compressed object a dict. Then use dictionary understanding to add the values of each key together.

d_1 = dict(zip(l_1, score))
d_2 = dict(zip(l_2, score))

{k: v + d_2[k] for k, v in d_1.items()}
# {'a': 3, 'b': 7, 'c': 4, 'd': 7, 'e': 9}

Related Problems and Solutions