Home > Back-end >  How to split a dictionary into a 9x9 2D array, consisting only of the dictionary values
How to split a dictionary into a 9x9 2D array, consisting only of the dictionary values

Time:05-17

If I have a dictionary, say

test_dict

and it contains 81 entries, in the current correct order.

How would I convert the dictionary's 81 values only into a 9x9 2D array? First 9 values make up the first 9 item array, second 9 values make up the second, and so on. Is it possible with numpy? I feel as though I'm missing something simple.

CodePudding user response:

You could try this. Here I have taken a dictionary having 4 elements. Extracted values from dictionary to a numpy array, then reshaped it to 2X2. You can reshape it to 9 by 9

import numpy as np

values = {1 : 1, 2 : 2, 3 : 2, 4 : 5}

vals = np.fromiter(values.values(), dtype=int)
print(vals.reshape(2,2))

Output:

[[1 2]
 [2 5]]
  • Related