Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dictionary in a numpy array?

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

like image 544
J. Doe Avatar asked Jun 21 '16 16:06

J. Doe


People also ask

Can we store dictionary in numpy 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.

Can you put a dictionary in an array?

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.

Can I have dictionary in array Python?

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.


2 Answers

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.

like image 196
Rodrigo Torres Avatar answered Oct 14 '22 18:10

Rodrigo Torres


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()
like image 38
user2357112 supports Monica Avatar answered Oct 14 '22 19:10

user2357112 supports Monica