H. Vabri
H. Vabri

Reputation: 314

itertools product of python dictionary values

I have a Python dictionary with strings as keys and numpy arrays as values:

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

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

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

As normally done when the items passed to product are numpy arrays.

When I do the following:

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

I get the following output instead:

[(array([3, 4]),), (array([1, 2]),)] 

Upvotes: 6

Views: 11526

Answers (1)

Raymond Hettinger
Raymond Hettinger

Reputation: 226346

The itertools.product() function expects the arguments to be unpacked into separate arguments rather than kept in a single mapping view. Use the * operator to do the unpacking:

>>> 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)]

Upvotes: 6

Related Questions