Dictionary in numpy array?

How to access a dictionary inside an array?

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

My initial thought:

 x['y'] 

Index Error: Invalid Index

 x[0] 

Index error: too many indexes for the array

+6
source share
2 answers

You have a 0-dimensional array of dtype object. Creating this array in general is probably a mistake, but if you still want to use it, you can extract the dictionary by indexing the array with a tuple without indexes:

 x[()] 

or by calling the array item method:

 x.item() 
+7
source

If you add square brackets to the destination of the array, you will have a 1-dimensional array:

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

then you can use:

 x[0]['y'] 

I believe this will make more sense.

+1
source

All Articles