Is there a function in python to convert an nd-array into a dictionary where key is a tuple of index and value is the matrix value at that index?
For example:
A = np.random.random([3,4,5])
Result:
{(i,j,k): A[i,j,k]}
You may use the data in numpy array to create a hash which could be used as a key for dictionary.
To convert a list to a dictionary using the same values, you can use the dict. fromkeys() method. To convert two lists into one dictionary, you can use the Python zip() function. The dictionary comprehension lets you create a new dictionary based on the values of a list.
You can use the get() method of the dictionary ( dict ) to get any default value without an error if the key does not exist. Specify the key as the first argument. The corresponding value is returned if the key exists, and None is returned if the key does not exist.
Sure: you can use np.ndenumerate
to accomplish this:
{ index: v for index, v in np.ndenumerate(A) }
Or simply, as DSM pointed out:
dict(np.ndenumerate(A))
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