How do I multiply two values in dictionary Python?

Question:

{'A': {5.0, 6.20}, 'B': {1.92, 3.35}, 'C': {3.21, 7.0}, 'D': {2.18, 9.90}}

I want to do an operation by where,i.e., if there’s a key match, let’s say on A, then I would multiply 5.0 and 6.20 and return that value.

Asked By: purple_plop

||

Answers:

You can use operator.mul(a, b) like the below:

from operator import mul

def mul_val(dct, key):
    # When a key does not exist, return 0*0, you can change it to what you want
    return mul(*dct.get(key, [0.0,0.0]))

dct = {'A': {5.0, 6.20}, 'B': {1.92, 3.35}, 'C': {3.21, 7.0}, 'D': {2.18, 9.90}}
print(mul_val(dct, 'A'))

Output:

31.0

Update base this comment:

from operator import mul

list1 = ['A', 'B', 'C', 'D']
list2 = [5.0, 1.92, 3.21, 2.18]
list3 = [6.2, 3.35, 7.0, 9.0]

# Option_1
output_1 = {x: y*z  for x, y, z in zip(list1, list2, list3)}

# Option_2
output_2 = {x: mul(*y) for x, *y in zip(list1, list2, list3)}

print(output_1)
# {'A': 31.0, 'B': 6.4319999999999995, 'C': 22.47, 'D': 19.62}

print(output_2)
# {'A': 31.0, 'B': 6.4319999999999995, 'C': 22.47, 'D': 19.62}
Answered By: I'mahdi
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.