10
votes

How do I access the dictionary inside the array?

import numpy as np
x = np.array({'x': 2, 'y': 5})

My initial thought:

x['y']

Index Error: not a valid index

x[0]

Index Error: too many indices for array

2

2 Answers

15
votes

You have a 0-dimensional array of object dtype. Making this array at all is probably a mistake, but if you want to use it anyway, you can extract the dictionary by indexing the array with a tuple of no indices:

x[()]

or by calling the array's item method:

x.item()
4
votes

If you add square brackets to the array assignment you will have a 1-dimensional array:

x = np.array([{'x': 2, 'y': 5}])

then you could use:

x[0]['y']

I believe it would make more sense.