Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert nd array to key, value dictionary

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]}
like image 822
deepAgrawal Avatar asked May 05 '17 18:05

deepAgrawal


People also ask

Can a Numpy array be a key in a dictionary?

You may use the data in numpy array to create a hash which could be used as a key for dictionary.

How do you change a list into a 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.

How do you get a dictionary key and value?

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.


1 Answers

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))
like image 162
brianpck Avatar answered Oct 14 '22 12:10

brianpck