recover dict from 0-d numpy array

烈酒焚心 提交于 2019-11-30 06:20:42

问题


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!


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/8361561/recover-dict-from-0-d-numpy-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!