recover dict from 0-d numpy array

PythonDictionaryLoadNumpySave

Python Problem Overview


What happened is that I (by mistake) saved a dictionary with the command numpy.save() (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')
mydict[0]['some_key'] 

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 numpy.save()?

Is there a way to recover the data?

Thanks in advance!

Python Solutions


Solution 1 - Python

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

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

Solution 2 - Python

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'>

Solution 3 - Python

It's a way to recover the dict type data that using 'allow_pickle=True' and '.tolist()'.
I hope it will help you.

numpy.save('mydict.npy', org_dict)

# load & convert type to dict
mydict = numpy.load('mydict.npy', allow_pickle=True)
re_dict = mydict.tolist()

print('re_dict :', type(re_dict), re_dict)   # 're_dict' is '<type dict>' 

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionandresView Question on Stackoverflow
Solution 1 - PythonunutbuView Answer on Stackoverflow
Solution 2 - PythonRobert KernView Answer on Stackoverflow
Solution 3 - PythonWangSungView Answer on Stackoverflow