Home > Enterprise >  TypeError: unhashable type: 'numpy.ndarray' when trying to append to a dictionary
TypeError: unhashable type: 'numpy.ndarray' when trying to append to a dictionary

Time:11-16

I'm trying to append values to my dictionary, but I can't solve this error.

This is my dictionary:

groups  = {'group1': array([450, 449.]), 'group2': array([490, 489.]), 'group3': array([568, 567.])}

then I have a txt file (loaded using np.loadtxt) with many data and I have to iterate over this file and if a certain condition is met I should add that line to the correct key of my dictionary. I used the if statement and I called the data that met the condition "parent".

parent = [[449. 448.]] 
[[489. 488.]] 
[[567. 566.]]

I tried this:

for i, x in enumerate(parent):
        groups.setdefault(x, []).append(i) 

expected output:

groups  = {'group1': array([450, 449.], [449, 448]), 'group2': array([490, 489.], [489, 488]), 'group3': array([568, 567.], [567, 566])}

but I get this error:

TypeError: unhashable type: 'numpy.ndarray'

CodePudding user response:

The reason why you got this error is that you tried to use data of unhashable type numpy.ndarray as the key of a dictionary. The links below are useful for your question.

A mapping object maps hashable values to arbitrary objects.

Raised when an operation or function is applied to an object of inappropriate type.


In your for loop, i is of type int which is hashable while x is of type numpy.ndarray which is unhashable. Therefore not using x as the key argument of groups.setdefault solves your TypeError problem.

P.S., there is still a way to go to get the expected groups. I don't show you the code, because it's not clear what the expected values of the dictionary are, a 2D array as value or a list of 1D arrays.

CodePudding user response:

As ILS noted, the problem description is unclear:

  1. are the output values a list or a 2D array?
  2. is parent a list of lists or some sort of array?
  3. is parent's size the same as groups's size?

Assuming same size lists, is this helping? -

groups  = {'group1': [[450., 449.]], 'group2': [[490., 489.]], 'group3': [[568., 567.]]}
parent = [[449., 448.],
[489., 488.],
[567., 566.]]
for i, x in enumerate(parent):
    groups[f'group{i 1}'].append(x)
groups

Returns:

{'group1': [[450.0, 449.0], [449.0, 448.0]],
 'group2': [[490.0, 489.0], [489.0, 488.0]],
 'group3': [[568.0, 567.0], [567.0, 566.0]]}
  • Related