0

I need to save a python dictionary of the format {key : [numpy array]} to a file (doesnt matter if the file is human readable or not, I just need to be able to retrieve it back into the same format later). I'd prefer to keep the numpy array as a numpy array as it is very large. Also the numpy array is 300dimensional so iterating through them would be impractical. I haven't seen any other questions asking this, because it doesn't look like I can use the numpy save methods as I am saving a dictionary. JSON does not work as the dictionary contains a numpy array. Does anyone know how I can do this? Thanks :)

1
  • Hello and welcome to Stack Overflow! Please see how to ask to further improve your question. It is important to make an honest attempt at the problem and then provide it to the community, along with expected and current results, so people can interact and help Commented Oct 29, 2021 at 20:13

1 Answer 1

1

The pickle module can handle numpy arrays. It is used almost exactly like the json module.

>>> import pickle
>>> import numpy as np
>>> a = np.arange(200).reshape((20,10))
>>> pickle.dump( a, open('xxx.bin','wb') )

... exit and reload ...

>>> import pickle
>>> pickle.load(open('xxx.bin','rb'))
array([[  0,   1,   2,   3,   4,   5,   6,   7,   8,   9],
       [ 10,  11,  12,  13,  14,  15,  16,  17,  18,  19],
       [ 20,  21,  22,  23,  24,  25,  26,  27,  28,  29],
       [ 30,  31,  32,  33,  34,  35,  36,  37,  38,  39],
       [ 40,  41,  42,  43,  44,  45,  46,  47,  48,  49],
       [ 50,  51,  52,  53,  54,  55,  56,  57,  58,  59],
       [ 60,  61,  62,  63,  64,  65,  66,  67,  68,  69],
       [ 70,  71,  72,  73,  74,  75,  76,  77,  78,  79],
       [ 80,  81,  82,  83,  84,  85,  86,  87,  88,  89],
       [ 90,  91,  92,  93,  94,  95,  96,  97,  98,  99],
       [100, 101, 102, 103, 104, 105, 106, 107, 108, 109],
       [110, 111, 112, 113, 114, 115, 116, 117, 118, 119],
       [120, 121, 122, 123, 124, 125, 126, 127, 128, 129],
       [130, 131, 132, 133, 134, 135, 136, 137, 138, 139],
       [140, 141, 142, 143, 144, 145, 146, 147, 148, 149],
       [150, 151, 152, 153, 154, 155, 156, 157, 158, 159],
       [160, 161, 162, 163, 164, 165, 166, 167, 168, 169],
       [170, 171, 172, 173, 174, 175, 176, 177, 178, 179],
       [180, 181, 182, 183, 184, 185, 186, 187, 188, 189],
       [190, 191, 192, 193, 194, 195, 196, 197, 198, 199]])
>>>
Sign up to request clarification or add additional context in comments.

1 Comment

The ONLY potential negative is that pickle is specific to Python. You can't (easily) pass it to another language. As long as you aware, it's a good solution.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.