Home > database >  Formatting the values of an array to be fitted within a dictionary
Formatting the values of an array to be fitted within a dictionary

Time:11-01

How can I set the numpy array a into three list sets within the dictionary dictionary as one, two, three just like the expected output below?

Code:

import numpy as np 
set_names = np.array(['one', 'two', 'three'])
a = np.array([12,4,2,45,6,7,2,4,5,6,12,4])
dictionary = {}

Expected output:

{
    'one': [12,4,2,45],
    'two': [6,7,2,4],
    'three': [5,6,12,4]
}

CodePudding user response:

Use np.array_split:

>>> dict(zip(set_names, np.array_split(a, len(set_names))))
{'one': array([12,  4,  2, 45]), 'two': array([6, 7, 2, 4]), 'three': array([ 5,  6, 12,  4])}
>>> 

As lists:

>>> {k: list(v) for k, v in zip(set_names, np.array_split(a, len(set_names)))}
{'one': [12, 4, 2, 45], 'two': [6, 7, 2, 4], 'three': [5, 6, 12, 4]}
>>> 

CodePudding user response:

You can simply try this approach with reshape.

import numpy as np

names = np.array(["one", "two", "three"])
a = np.array([12, 4, 2, 45, 6, 7, 2, 4, 5, 6, 12, 4])
dictionary = {}
for i, name in enumerate(names):
    dictionary[name] = list(a.reshape(len(names), -1)[i])

print(dictionary)

This gives the following output.

{'one': [12, 4, 2, 45], 'two': [6, 7, 2, 4], 'three': [5, 6, 12, 4]}

Or if you want a one-liner, here is the equivalent dict comprehension for it.

print({name: list(a.reshape(len(names), -1)[i]) for i, name in enumerate(names)})

This gives the following output.

{'one': [12, 4, 2, 45], 'two': [6, 7, 2, 4], 'three': [5, 6, 12, 4]}
  • Related