Home > OS >  Merging 2 numpy arrays into a dictionary
Merging 2 numpy arrays into a dictionary

Time:10-21

I have 2 numpy darrays and want to create a dictionary from them. For example {(7.9,3.8,6.4,2): 2}

import numpy as np

little_X_test= np.array([[7.9, 3.8, 6.4, 2],
 [5.2, 4.1, 1.5, 0.1],
 [6.9, 3.1, 5.1, 2.3]])
little_y_test= np.array([2, 0, 2])

d = {}
for A, B in zip(little_X_test, little_y_test):
    d[A] = B

Error message

TypeError: unhashable type: 'numpy.ndarray'

CodePudding user response:

Numpy arrays, lists, and other mutable object are non hashable.

If you convert to tuple this works as the object is immutable.

NB. You don't have to use a loop, use the dict constructor directly

import numpy as np

little_X_test= np.array([[7.9, 3.8, 6.4, 2],
                         [5.2, 4.1, 1.5, 0.1],
                         [6.9, 3.1, 5.1, 2.3]])
little_y_test= np.array([2, 0, 2])

d = dict(zip(map(tuple, little_X_test), little_y_test))

output:

>>> d
{(7.9, 3.8, 6.4, 2.0): 2,
 (5.2, 4.1, 1.5, 0.1): 0,
 (6.9, 3.1, 5.1, 2.3): 2}
  • Related