Itertools python dictionary value product

I have a Python dictionary with strings in the form of keys and numpy arrays as values:

dictionary = {'first': np.array([1, 2]), 'second': np.array([3, 4])}

Now I want to use itertools productto create the following list:

requested = [(1, 3), (1, 4), (2, 3), (2, 4)]

As usual, when the elements passed in productare numpy arrays.

When I do the following:

list(product(list(dictionary.values())))

Instead, I get the following output:

[(array([3, 4]),), (array([1, 2]),)] 
+4
source share
1 answer

The itertools.product () function expects the arguments to be unpacked into separate arguments, and not stored in the same display view. Using the *operator, unpack:

>>> import numpy as np
>>> from itertools import product
>>> dictionary = {'first': np.array([1, 2]), 'second': np.array([3, 4])}
>>> list(product(*dictionary.values()))
[(1, 3), (1, 4), (2, 3), (2, 4)]
+1
source

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


All Articles