Creating a Cartesian product for n different types

Consider that I have a dict containing n different types represented by keys: x1, x2 ..xn

For simplicity, take a small example:

{"x1":["foo1", "goo1" ,"doo1"], "x2":["foo2","goo2"]}

I want to calculate the Cartesian product above. My conclusion should be:

{"output":[{"x1":"foo1", "x2":"foo2"}, {"x1":"foo1", "x2":"goo2"}, {"x1":"goo1", "x2":"foo2"} , {"x1":"goo1", "x2":"goo2"}, {"x1":"doo1", "x2":"foo2"} {"x1":"doo1", "x2":"goo2"}]}

Should I traverse each unique pairof the dictionary input keys and compute their Cartesian products and add their values? How to combine other values ​​if another value appears, say, x3?

With this approach, I calculate the Cartesian product for the values ​​x1 * x2 and then the values ​​x2 * x3 and how to combine the results in x1 * x2 * x3?

Can you come up with a simpler and more efficient algorithm? Or should it be so?

+4
source share
2

itertools.product . - dicts, (.keys .values Python, dict ), , . , - dicts zip:

from itertools import product
from pprint import pprint

dct = {"x1":["foo1", "goo1" ,"doo1"], "x2":["foo2","goo2"]}

keys = list(dct)
lst = [dict(zip(keys, vals)) for vals in product(*[dct[k] for k in keys])]
pprint(lst)

[{'x1': 'foo1', 'x2': 'foo2'},
 {'x1': 'foo1', 'x2': 'goo2'},
 {'x1': 'goo1', 'x2': 'foo2'},
 {'x1': 'goo1', 'x2': 'goo2'},
 {'x1': 'doo1', 'x2': 'foo2'},
 {'x1': 'doo1', 'x2': 'goo2'}]

, .

+4

product itertools :

from itertools import product

a = {"x1":["foo1", "goo1" ,"doo1"], "x2":["foo2","goo2"]}
final = [{i:j for i, j in zip(a.keys(), k)} for k in product(*a.values())]
# Or:
# final = [dict(zip(a.keys(), k)) for k in product(*a.values())]
# Or:
# final = list(map(lambda x: dict(zip(a.keys(), x)), product(*a.values())))

print(final)

:

[{'x1': 'foo1', 'x2': 'foo2'},
 {'x1': 'foo1', 'x2': 'goo2'},
 {'x1': 'goo1', 'x2': 'foo2'},
 {'x1': 'goo1', 'x2': 'goo2'},
 {'x1': 'doo1', 'x2': 'foo2'},
 {'x1': 'doo1', 'x2': 'goo2'}]
0

Source: https://habr.com/ru/post/1678965/


All Articles