save each row of dictionary array to numpy(.npy) file

Viewed 30

I have a list and dictionary like below and want to save each row of dictionary as numpy file.

lists=['first_data','second_data']
dict_array=
{'1': array([[1., 1., 2., 2.], #here represents'first_data'
[3., 3., 4., 4.]]), #here represents 'second data'
 '2': array([[10., 1., 21., 1.], #here represents'first_data'
[24., 12., 32., 33.]])} #here represents 'second data'

For each row in each array, I want to save it as numpy file with it's name on it.

For example, for dict_array['1'], the first row should have '1_first_data.npy', and for dict_array['2'], the second row should have '2_second_data.npy'.

I only read each row of dictionary but need help for next steps.

for i,a in dict_array.items():
   for row in a:
      row.tofile(str...)
1 Answers

You can do it like this:

for key, values in dict_array.items():
     [np.save(f'{key}_{label}.npy', value) for (label, value) in zip(lists, values)]

I implemented it such that you could also add a 'third_data' to your dictionary since the list comprehension iterates over all arrays that are given in the values of your dictionary.

Related