Skip to content Skip to sidebar Skip to footer

Numpy: Create Array From A (index,value) Dict

I have a dict of the form: {1: 5, 2: 1, 4: 6, 8: 9} and I want to convert it to an array of the form: [0, 5, 1, 0, 6, 0, 0, 0, 9]. So the keys represent indexes into the array and

Solution 1:

As simple as dict.get.

>>> np.array([d.get(i, 0) for i in range(max(d) + 1)])
array([0, 5, 1, 0, 6, 0, 0, 0, 9])

Post a Comment for "Numpy: Create Array From A (index,value) Dict"