Python : save dictionaries through numpy.save [duplicate] Python : save dictionaries through numpy.save [duplicate] numpy numpy

Python : save dictionaries through numpy.save [duplicate]


It's a structured array. Use d2.item() to retrieve the actual dict object first:

import numpy as npd1={'key1':[5,10], 'key2':[50,100]}np.save("d1.npy", d1)d2=np.load("d1.npy")print d1.get('key1')print d2.item().get('key2')

result:

[5, 10][50, 100]


pickle module can be used. Example code:

from six.moves import cPickle as pickle #for performancefrom __future__ import print_functionimport numpy as npdef save_dict(di_, filename_):    with open(filename_, 'wb') as f:        pickle.dump(di_, f)def load_dict(filename_):    with open(filename_, 'rb') as f:        ret_di = pickle.load(f)    return ret_diif __name__ == '__main__':    g_data = {        'm':np.random.rand(4,4),        'n':np.random.rand(2,2,2)    }    save_dict(g_data, './data.pkl')    g_data2 = load_dict('./data.pkl')    print(g_data['m'] == g_data2['m'])    print(g_data['n'] == g_data2['n'])

You may also save multiple python objects in a single pickled file. Each pickle.load call will load a single object in that case.