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