Creating a dictionary from a numpy array

I have a numpy array and I want to create a dictionary from an array.

In particular, I want the dictionary to have the keys corresponding to the string, so key 1 should be the sum of string 1.

s1 is my array, and I know how to get the sum of the string, but do numpy.sum(s1[i]) , where I am the string.

I was thinking of creating a loop where I can calculate the sum of a string and then add it to the dictionary, but I'm new to programming, so I'm not sure how to do this or if it's possible.

Does anyone have any suggestions?

EDIT

I created key values ​​using a range function. Then secure the keys and array.

 mydict = dict(zip(keys, s1)) 
+7
python dictionary arrays numpy
source share
1 answer

I would do something similar to the spirit of your dict(zip(keys, s1)) with two minor changes.

First, we can use enumerate , and secondly, we can call the sum method of ndarray s. Example:

 >>> arr = np.arange(9).reshape(3,3) >>> arr array([[0, 1, 2], [3, 4, 5], [6, 7, 8]]) >>> arr.sum(axis=1) array([ 3, 12, 21]) >>> dict(enumerate(arr.sum(axis=1))) {0: 3, 1: 12, 2: 21} 
+8
source share

All Articles