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
We can use Python's numpy. save() function from transforming an array into a binary file when saving it. This method also can be used to store the dictionary in Python.
You cannot use string indexes in arrays, but you can apply a Dictionary object in its place, and use string keys to access the dictionary items. The dictionary object has the following benefits when compared with arrays: The size of the Dictionary object can be set dynamically.
A dictionary in Python constitutes a group of elements in the form of key-value pairs. A list can store elements of different types under a common name and at specific indexes. In Python, we can have a list or an array of dictionaries. In such an object, every element of a list is a dictionary.
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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With