user2926009
user2926009

Reputation: 155

Creating dictionary from numpy array

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

More specifically I want a dictionary that has keys that correspond to the row, so key 1 should be the sum of row 1.

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

I was thinking of creating a loop where I can compute the sum of the row and then add it to a dictionary but I am new to programming so I am not sure how to do this or if it is possible.

Does anybody have any suggestions?

EDIT

I created the key values with the range function. Then zipped the keys and the array.

mydict = dict(zip(keys, s1))

Upvotes: 15

Views: 61434

Answers (1)

DSM
DSM

Reputation: 353019

I'd do something similar in spirit to your dict(zip(keys, s1)), with two minor changes.

First, we can use enumerate, and second, we can call the sum method of ndarrays. 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}

Upvotes: 22

Related Questions