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))
You may use the data in numpy array to create a hash which could be used as a key for dictionary.
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 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}
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