Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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]),)] 
like image 768
H. Vabri Avatar asked Nov 29 '16 15:11

H. Vabri


People also ask

How do we fetch values from dictionary in Python?

In Python, you can get the value from a dictionary by specifying the key like dict[key] . In this case, KeyError is raised if the key does not exist. Note that it is no problem to specify a non-existent key if you want to add a new element.

What is Product () in Python?

product() is a part of a python module itertools; a collection of tools used to handle iterators. Together all these tools form iterator algebra. Itertools will make your code stand out. Above all, it will make it more pythonic.

What does item () and key () methods of dictionary return?

The items () method in the dictionary is used to return each item in a dictionary as tuples in a list. Thus, the dictionary key and value pairs will be returned in the form of a list of tuple pairs. The items () method does not take any parameters.

Can we search in values of dictionary Python?

In this Program, we will discuss how to find the value by key in Python dictionary. By using the dict. get() function, we can easily get the value by given key from the dictionary. This method will check the condition if the key is not found then it will return none value and if it is given then it specified the value.


1 Answers

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)]
like image 161
Raymond Hettinger Avatar answered Oct 02 '22 17:10

Raymond Hettinger