8

I have a dictionary:

mydict = {'item1':[1,2,3],'item2':[10,20,30]}

I want to create the cartesian product of the two so that I get a 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 like there would be a simple way to do this so that it extends if I have three items. Kind of like a dynamic number of loops. Feels like I am missing an obvious way to do this...

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Chris
  • 12,900
  • 12
  • 43
  • 65

4 Answers4

13

The itertools.product() function will do 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 you need to control the order of the resulting tuples, you can do

itertools.product(mydict['item1'], mydict['item2'])
Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285
2

You can also brute force it using two loops

mydict = {'item1':[1,2,3],'item2':[10,20,30]}

x = []
for i in mydict['item1']:
    for j in mydict['item2']:
        x.append((i,j))

All this code does is go through all of the item in mydict['item1'], then through each item in mydict['item2'], then appends a pair of each to a new list.

It will give you this result:

[(1, 10), (1, 20), (1, 30), (2, 10), (2, 20), (2, 30), (3, 10), (3, 20), (3, 30)]
michaelpri
  • 3,521
  • 4
  • 30
  • 46
1

You can use List Comprehensions:

[(i, j) for i in mydict['item1'] for j in mydict['item2']]
kmkaplan
  • 18,655
  • 4
  • 51
  • 65
0

you could do two for loops. - the first one would keep track of the index position of the first item list. -The second loop would go through each item in the second. - After it runs through all the items, the first for loop would increment to the next item in its list and the second loop will run through the second list again, etc.