Storing a dict with np.savez gives unexpected result? Storing a dict with np.savez gives unexpected result? numpy numpy

Storing a dict with np.savez gives unexpected result?


It is possible to recover the data:

In [41]: a = {'0': {'A': array([1,2,3]), 'B': array([4,5,6])}}In [42]: np.savez('/tmp/model.npz', **a)In [43]: a = np.load('/tmp/model.npz')

Notice that the dtype is 'object'.

In [44]: a['0']Out[44]: array({'A': array([1, 2, 3]), 'B': array([4, 5, 6])}, dtype=object)

And there is only one item in the array. That item is a Python dict!

In [45]: a['0'].sizeOut[45]: 1

You can retrieve the value using the item() method (NB: this is not theitems() method for dictionaries, nor anything intrinsic to the NpzFileclass, but is the numpy.ndarray.item() methodthat copies the value in the array to a standard Python scalars. In an array of object dtype any value held in a cell of the array (even a dictionary) is a Python scalar:

In [46]: a['0'].item()Out[46]: {'A': array([1, 2, 3]), 'B': array([4, 5, 6])}In [47]: a['0'].item()['A']Out[47]: array([1, 2, 3])In [48]: a['0'].item()['B']Out[48]: array([4, 5, 6])

To restore a as a dict of dicts:

In [84]: a = np.load('/tmp/model.npz')In [85]: a = {key:a[key].item() for key in a}In [86]: a['0']['A']Out[86]: array([1, 2, 3])


Based on this answer: recover dict from 0-d numpy array

After

a = {'key': 'val'}scipy.savez('file.npz', a=a) # note the use of a keyword for ease later

you can use

get = scipy.load('file.npz')a = get['a'][()] # this is crazy maybe, but trueprint a['key']

It would also work without the use of a keyword argument, but I thought this was worth sharing too.