Skip to content
Advertisement

How to create a list from a dict of lists that has combinations of the array elements [closed]

The question might have been worded confusingly so here I will try to make it more clear. Suppose I have a dict like x = {0: [(36, 44)], 1: [(38, 39), (38, 40), (39, 40)], 2: [(37, 41), (37, 42), (41, 42)], 3: [(43,)], 4: [(45,)]}

I want to create a list with all possible combinations of 1 element from each of the array. E.g. – [(36,44),(38,39),(37,41),(43),(45)] is one such combination, [(36,44),(38,40),(37,41),(43),(45)] is another. The final list should have all such combinations.

For now as I know the key values, I tried doing it as

arr_0 = x[0]

arr_1 = x[1]

arr_2 = x[2]

arr_3 = x[3]

arr_4 = x[4]

and then finally,

y = itertools.product(arr_0, arr_1, arr_2, arr_3, arr_4)

which produces the answer

((36, 44), (38, 39), (37, 41), (43,), (45,))

((36, 44), (38, 39), (37, 42), (43,), (45,))

((36, 44), (38, 39), (41, 42), (43,), (45,))

((36, 44), (38, 40), (37, 41), (43,), (45,))

((36, 44), (38, 40), (37, 42), (43,), (45,))

((36, 44), (38, 40), (41, 42), (43,), (45,))

((36, 44), (39, 40), (37, 41), (43,), (45,))

((36, 44), (39, 40), (37, 42), (43,), (45,))

((36, 44), (39, 40), (41, 42), (43,), (45,))

In a scenario where I do not the keys of the dict and the array sizes, how can I create the final array ?

Advertisement

Answer

You may use itertools.product and pass it the different arrays thta you need

from itertools import product

x = {0: [(36, 44)], 1: [(38, 39), (38, 40), (39, 40)], 2: [(37, 41), (37, 42)]}

for p in product(*x.values()):
    print(p)

((36, 44), (38, 39), (37, 41))
((36, 44), (38, 39), (37, 42))
((36, 44), (38, 40), (37, 41))
((36, 44), (38, 40), (37, 42))
((36, 44), (39, 40), (37, 41))
((36, 44), (39, 40), (37, 42))

The x.values() is a list of list of values (tuples) [[(36, 44)], [(38, 39), (38, 40), (39, 40)], [(37, 41), (37, 42)]], the * is here to expand them and pass each sublist a different parameter of the method


For you to get it, a smaller example

for p in product([1, 2], [3], (5, 6)):
    print(p)
    
(1, 3, 5)
(1, 3, 6)
(2, 3, 5)
(2, 3, 6)
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement