lilis gumilang
lilis gumilang

Reputation: 19

How to multiply a tuple?

I want to multiply a tuple.

y = 0.1, 0.2, 0.2, 0.4, 0.1
x = {('S', 'A', 'C', 'T'): (0.2, 0.1, 0.9, 3, 4), ('S', 'C', 'T'): (0.4. 0.1, 0.3, 3,1)}

Expected output:

res = {('S', 'A', 'C', 'T'): (0.02, 0.02, 0.18, 1.2, 0.4), ('S', 'C', 'T'): (0.04. 0.02, 0.06, 1.2, 0.1)}

My code is:

from fuctools import partial:
res = {}
keys = list(set.keys())
vals = list(set.values())
mul = lambda x, y: x*y
for n in vals:
   res.extend(map(partial(mul, x), y))
res = dict(res)
print(res)   

But it causes an error that the dict has no attribute 'extend'.

Upvotes: 0

Views: 2419

Answers (3)

Mykola Zotko
Mykola Zotko

Reputation: 17854

You can use the function starmap() with the operator mul inside a dictcomp:

from itertools import starmap
from operator import mul

y = 0.1, 0.2, 0.2, 0.4, 0.1
x = {('S', 'A', 'C', 'T'): (0.2, 0.1, 0.9, 3, 4), ('S', 'C', 'T'): (0.4, 0.1, 0.3, 3, 1)}

{k: tuple(starmap(mul, zip(v, y))) for k, v in x.items()}
# {('S', 'A', 'C', 'T'): (0.020000000000000004, 0.020000000000000004, 0.18000000000000002, 1.2000000000000002, 0.4), ('S', 'C', 'T'): (0.04000000000000001, 0.020000000000000004, 0.06, 1.2000000000000002, 0.1)}

Alternatively you can use numpy.multiply():

import numpy as np

y = 0.1, 0.2, 0.2, 0.4, 0.1
x = {('S', 'A', 'C', 'T'): (0.2, 0.1, 0.9, 3, 4), ('S', 'C', 'T'): (0.4, 0.1, 0.3, 3, 1)}

{k: np.multiply(v, y) for k, v in x.items()}
# {('S', 'A', 'C', 'T'): array([0.02, 0.02, 0.18, 1.2 , 0.4 ]), ('S', 'C', 'T'): array([0.04, 0.02, 0.06, 1.2 , 0.1 ])}

Upvotes: 1

Hari
Hari

Reputation: 1623

We can do like follow

from itertools import starmap
import operator
final_dict = { key: list(starmap(operator.mul, zip(value, y))) for key, value in x.items() }
for key, value in final_dict.items():
   print(value)

Upvotes: 0

J. Taylor
J. Taylor

Reputation: 4865

This should do the trick:

y = 0.1, 0.2, 0.2, 0.4, 0.1
x = {('S', 'A', 'C', 'T'): (0.2, 0.1, 0.9, 3, 4), ('S', 'C', 'T'): (0.4, 0.1, 0.3, 3,1)}

for k, v in x.items():
    x[k] = tuple(v[i] * y[i] for i in range(len(y)))

Or alternatively (as Alex Hall suggested in the comment below) you could use the zip function like this:

for k in x.keys():
    x[k] = tuple(a[0] * a[1] for a in zip(y, x[k]))

I would suggest using one of the above instead of your original approach. But for future reference, the reason you are getting the error dict has no attribute 'extend' is that extend() is a method for lists, not for dictionaries. When you attempt to call res.extend() it is throwing this exception because res is a dict, not a list. If you want to add multiple key/value pairs to a dict, use the update() method.

Upvotes: 2

Related Questions