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...
You can loop through the list items by using a while loop. Use the len() function to determine the length of the list, then start at 0 and loop your way through the list items by referring to their indexes.
Using Python for loop to iterate over a list. In this syntax, the for loop statement assigns an individual element of the list to the item variable in each iteration. Inside the body of the loop, you can manipulate each list element individually.
You can use a for loop to create a list of elements in three steps: Instantiate an empty list. Loop over an iterable or range of elements. Append each element to the end of the list.
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'])
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)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With