15

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

3 Answers 3

23

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()
Sign up to request clarification or add additional context in comments.

2 Comments

Ok, Nvidia Modulus uses this kind of numpy array to export model's output. This was super useful.
I ended up with such a 0-dimensional array after using np.savez_compressed to save a few variables, including a dict, and then loading them again. I was as perplexed as OP, so this is still a relevant answer, thank you!
4

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.

Comments

0
# json & dict -> tuple 
djson = json.loads('{"Foo": "bar", "Loreum": "ipsum"}') # json -> dict
dict2tupls = []
n = 0
for i in djson.items():
    dict2tupls += [i]

make_nparray = np.array(dict2tupls)

print(dict2tupls)
print(make_nparray)
print(make_nparray.shape)

Dictionary:

[('Foo', 'bar'), ('Loreum', 'ipsum')]

nparray:

[['Foo', 'bar'], ['Loreum', 'ipsum']]

nparray Dimensions:

(2, 2)

This is the solution I came up with, convert keys:value into tuples. Handle dimensions accordingly..

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.