简体   繁体   中英

python - save dict to .npy format

I have a dict and I associate an array to each key (the key itself is a number).

Minimal example:

import numpy as np
data = {}
data[2.5] = np.array([np.array([1,2,3,4]), np.array([5,6,7,8])])

Then I save the dict :

np.save('file.npy', data)

and then reload it:

datanew = np.load('file.npy')

--

Now, in order to access what is stored in each key, I cannot just do:

datanew[2.5]

But I have to do

datanew[()][2.5]
  • Why?
  • Is there a better way to save dicts?

The reason is because np.save 's arr argument expects an array. When you passed a dictionary it instead saved it as a one by one 'dimensionless' array. So when you load it, you need to get the 'first' element out of that dimensionless array (ie [()] ). You could just do this when you call np.load though and then never worry about it again:

datanew = np.load('file.npy')[()]

Alternatively since you're trying to save a dictionary you could use pickle. np.save is suppose to be optimized for numerical arrays, I don't know if you still get the benefits it you've put your arrays in a dictionary though...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM