I have a dictionary like this containing tuples:
d = {'itemA': (1, 0.5), 'itemB': (2, 0.3), 'itemC': (3, 0.7)}
How can I multiply each tuple individually and then take the overall sum?
result = (1 * 0.5) (2 * 0.3) (3 * 0.7) = 3.2
CodePudding user response:
Plain Python:
d = {'itemA': (1, 0.5), 'itemB': (2, 0.3), 'itemC': (3, 0.7)}
sum_tot = 0
for tpl in d.values():
prod_tpl = 1
for item in tpl:
prod_tpl *= item
sum_tot = prod_tpl
print(sum_tot)
Output:
3.1999999999999997
CodePudding user response:
You can do this:
from functools import reduce
from operator import mul
d = {'itemA': (1, 0.5), 'itemB': (2, 0.3), 'itemC': (3, 0.7)}
d1={k:reduce(mul, t) for k,t in d.items()}
>>> sum(d1.values())
3.1999999999999997
Or simply:
>>> sum(reduce(mul, t) for t in d.values())
3.1999999999999997
Or, an even better way pointed out in comments:
import math
>>> sum(map(math.prod, d.values()))
3.1999999999999997
CodePudding user response:
d = {'itemA': (1, 0.5), 'itemB': (2, 0.3), 'itemC': (3, 0.7)}
result = 0
for item in d:
result = d[item][0] * d[item][1]
print(result)
CodePudding user response:
d = {'itemA': (1, 0.5), 'itemB': (2, 0.3), 'itemC': (3, 0.7)}
total = 0
for tup in d.values():
total = tup[0]*tup[1]
print(total)