I have a dictionary of the following format:
{1: 7, 2: 1, 4: 2, 5: 1, ...}
The dictionary can be potentially very large, so I decided to use numpy library for more efficient work with vectors.
Now I need to insert values from the above dictionary in a numpy vector (1-dimensional array) at the key index. So tried naively the following:
import numpy as np
d = {1: 7, 2: 1, 4: 2, 5: 1}
T = np.zeros(shape=(n), dtype=np.int16)
for k, v in d.items():
N = np.insert(T, k, v)
print(N)
However insert method always returns new array, and overwrites N in my example. So what is the right way to change array elements, just as I'd do in C, e.g. T[0] = 1.
Looks like numpy does not allow this?
Thanks.
UPDATE As suggested by Divakar, the solution is to assign multiple values at once:
T[list(d.keys())] = list(d.values())
And this does not require a loop.
nparameter?T[list(d.keys())] = list(d.values())?numpyarray object can take a list as parameter?numpy array object taking a list as parameter. It's a simple integer based indexding - docs.scipy.org/doc/numpy/reference/…list(d.keys())which returns a list of keys from dictionary, and then submit it as index toTobject.