python - Loop for each item in a list -
i have dictionary:
mydict = {'item1':[1,2,3],'item2':[10,20,30]}
i want create cartesian product of 2 tuple of each possible pair.
output: [(1,10),(1,20),(1,30), (2,10),(2,20),(2,30), (3,10),(3,20),(3,30)]
it seems there simple way extends if have 3 items. kind of dynamic number of loops. feels missing obvious way this...
the itertools.product()
function this:
>>> import itertools >>> mydict = {'item1':[1,2,3],'item2':[10,20,30]} >>> list(itertools.product(*mydict.values())) [(10, 1), (10, 2), (10, 3), (20, 1), (20, 2), (20, 3), (30, 1), (30, 2), (30, 3)]
if need control order of resulting tuples, can do
itertools.product(mydict['item1'], mydict['item2'])
Comments
Post a Comment