0

In Python 3.7, Numpy: I saved and loaded a dict, using numpy (like I already asked here: Saving a sequence of 3rd-order Tensors and reading it back without losing array format ).

Loading it merges it to one big thing where i cannot get the single values anymore.

I used np.save('filename', dict) to save a dictionary like {(1, 0): 1, (1, 1): 2, (2, 0): 3, (2, 1): 4} and loaded_dict = np.load('filename.npy', allow_pickle=True) to load an object what I need to be a dictionary.

Now just trying to do loaded_dict[(1, 0)] does not work. In fact: print(loaded_dict.shape) outputs ().

Working example code:

import numpy as np

example_dict = {(1, 0): 1, (1, 1): 2, (2, 0): 3, (2, 1): 4}
np.save('filename', example_dict)

loaded_dict = np.load('filename.npy', allow_pickle=True)
print(loaded_dict) # Works just fine, prints out the example dict
print(type(loaded_arrs)) # Outputs <class 'numpy.ndarray'>
print(loaded_dict.shape) # Outputs ()
print(loaded_dict[(1, 0)]) # Does not work, Error below

Output:

{(1, 0): 1, (1, 1): 2, (2, 0): 3, (2, 1): 4}
<class 'numpy.ndarray'>
()
IndexError: too many indices for array

I really only need the numbers 1, 2, 3, 4 in that order. Originally I wanted to use the tuples aswell but getting the numbers (in order!) only is enough.

Also: Those numbers are lists in the original. I kept that out of the code to make it more readable. How much of a problem would that be to fix? If you only have a solution for integers, I can use that aswell!

Any help would be very appreciated. I already have an file of 127 KB which took 11 hours to produce, so preferably I would like to make something out of what i already have. If that is impossible or too complicated then I can do a completely fresh start, but only as a last resort.

Jason D.
  • 47
  • 7
  • Oh yeah. Somehow that did not show up when I searched for it, or I must have overlooked it. Sorry. – Jason D. Jun 17 '19 at 14:55
  • 1
    When shape is `()`, you can access the element with an empty tuple, `loaded_dict[()]`. But `item()` does just as well. – hpaulj Jun 17 '19 at 16:22

1 Answers1

1

loaded_dict is a numpy.ndarray not a dictionary. You can access the dictionary using .item() method,

loaded_dict.item()[(1, 0)]

If you want to access all the dictionary values you can use,

for key,value in loaded_dict.item().items():
    print(value)
GeoMSI
  • 144
  • 8