How to get a all combinations of two dictionnaries to make a new one in Python

Question:

I want to get all combinations on two dictionnaries to get a new one:

d1={'a':1.2,'b':1.5,'c':1.3}
d1={'a':2,'b':1,'c':2}

into:

d={('a','a'):2.4,('a','b'):1.2,('a','c'):2.4,...}

where the new keys will be the combinations the initials dicts, ex: ('a','a') and the new values will be the product of previous values, ex: 1.2 * 2 = 2.4

Asked By: zoldxk

||

Answers:

Assuming you want the product of the values, you can use:

d1={'a':1.2,'b':1.5,'c':1.3}
d2={'a':2,'b':1,'c':2}

from itertools import product

out = {k: d1[k[0]]*d2[k[1]] for k in product(d1, d2)}
# or
out = {(k1, k2): d1[k1]*d2[k2] for k1, k2 in product(d1, d2)}

Generic answer for an arbitrary number of dictionaries:

from itertools import product
from math import prod

dicts = [d1, d2]

out = {k: prod(d[key] for key,d in zip(k,dicts))
       for k in product(*dicts)}

Output:

{('a', 'a'): 2.4,
 ('a', 'b'): 1.2,
 ('a', 'c'): 2.4,
 ('b', 'a'): 3.0,
 ('b', 'b'): 1.5,
 ('b', 'c'): 3.0,
 ('c', 'a'): 2.6,
 ('c', 'b'): 1.3,
 ('c', 'c'): 2.6}
Answered By: mozway
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.