jim
jim

Reputation: 53

Multiply tuple values in dictionary and take final sum

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

Upvotes: 0

Views: 180

Answers (4)

Thisal
Thisal

Reputation: 310

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)

Upvotes: 0

Gazi Ashiq
Gazi Ashiq

Reputation: 26

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)

Upvotes: 0

dawg
dawg

Reputation: 103959

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

Upvotes: 1

andthum
andthum

Reputation: 85

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

Upvotes: 1

Related Questions