python – recover dict from 0-d numpy array-ThrowExceptions

Exception or error:

What happened is that I (by mistake) saved a dictionary with the command (no error messages shown) and now I need to recover the data in the dictionary. When I load it with numpy.load() it has type (numpy.ndarray) and is 0-d, so it is not a dictionary any more and I can’t access the data in it, 0-d arrays are not index-able so doing something like

mydict = numpy.load('mydict')

doesn’t work. I also tried

recdict = dict(mydict)

but that didn’t work either.

Why numpy didn’t warn me when I saved the dictionary with

Is there a way to recover the data?

Thanks in advance!

How to solve:

Use mydict.item() to obtain the array element as a Python scalar.

>>> import numpy as np
>>>'/tmp/data.npy',{'a':'Hi Mom!'})
>>> x=np.load('/tmp/data.npy')
>>> x.item()
{'a': 'Hi Mom!'}


0-d arrays can be indexed using the empty tuple:

>>> import numpy as np
>>> x = np.array({'x': 1})
>>> x
array({'x': 1}, dtype=object)
>>> x[()]
{'x': 1}
>>> type(x[()])
<type 'dict'>

Leave a Reply

Your email address will not be published. Required fields are marked *