Dictionary in a numpy array?

2019-02-22 01:25发布

问题:

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

回答1:

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()


回答2:

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.