The error TypeError: unhashable type: ‘numpy.ndarray’ occurs when trying to get a hash of a NumPy ndarray. For example, using an ndarray as a key in a Python dictionary because you can only use hashable data types as a key.

We can use the update() method to add a ndarray directly to a set. We can use the elements of an ndarray as the keys of a dictionary, provided the elements are hashable.

This tutorial will go through the error in detail and how to solve it with the help of code examples.


TypeError: unhashable type: ‘numpy.ndarray’

What Does TypeError Mean?

TypeError occurs whenever you try to perform an illegal operation for a specific data type object. In the example, the illegal operation is hashing, and the data type is numpy.ndarray.

What Does Unhashable Mean?

By definition, a dictionary key needs to be hashable. An object is hashable if it has a hash value that remains the same during its lifetime. A hash value is an integer Python uses to compare dictionary keys while looking at a dictionary.

When we add a new key:value pair to a dictionary, the Python interpreter generates a hash of the key.

Similarly, we can think of a set as a dictionary that only contains the keys, so it also requires hashable items.

We can only hash particular objects in Python, like strings or integers. All immutable built-in objects in Python are hashable, for example, tuple, and mutable containers are not hashable, for example, list.

Example #1: Converting a Multi-dimension NumPy array to a Set

We can convert an iterable object like a list or a NumPy array to a set using the built-in set() method. When we call the set() method on the iterable object, the Python interpreter checks whether the elements in the iterable are hashable or not. If the elements are hashable, we can successfully convert the iterable object to a set object.

Let’s look at an example where we convert a one-dimension NumPy ndarray to a set:

import numpy as np

arr = np.array([1, 3, 5, 7])

print(set(arr))
{1, 3, 5, 7}

We successfully get a set because the array elements are of integer type. In Python, int is a hashable type.

Next, let’s try to convert a multi-dimensional ndarray to a set:

import numpy as np

arr = np.array([[1, 3, 5, 7],[1, 4, 5, 8]])

print(set(arr))
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
      3 arr = np.array([[1, 3, 5, 7],[1, 4, 5, 8]])
      4 
----≻ 5 print(set(arr))

TypeError: unhashable type: 'numpy.ndarray'

We raise the error because the elements of the array is a ndarray array object, and Ndarray objects are not hashable.

print(type(arr[0]))
print(type(arr[1]))
≺class 'numpy.ndarray'≻
≺class 'numpy.ndarray'≻

Solution

We separate the multi-dimensional array into its component arrays and add their values to the set to solve this error. Let’s look at the code:

import numpy as np

arr = np.array([[1, 3, 5, 7],[1, 4, 5, 8]])

a_set = set()

for i in arr:

    a_set.update(set(i))

print(a_set)

In the above code, we use a for loop to iterate over the component arrays in the multi-dimensional array; we convert each array to a set and call the update() method on a set object to contain the values for all the arrays. Let’s run the code to see the result:

{1, 3, 4, 5, 7, 8}

Example #2: Using a NumPy NDarray as a Key in a Dictionary

We can only use hashable objects as a key in a Python dictionary. If we use any unhashable objects as a dictionary key, we will raise the TypeError. Let’s look at an example:

import numpy as np

arr = np.array([0])

a_dict = dict()

a_dict[arr] = "X"

print(a_dict)

In the above code, we define a numpy array with one element and attempt to use it as a key in a dictionary. Let’s run the code to see the result:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
----≻ 1 a_dict[arr] = "X"

TypeError: unhashable type: 'numpy.ndarray'

Solution

To solve this error, we need to access the element of the array as they are unhashable and use this as the key to the dictionary. Let’s look at the revised code:

import numpy as np

arr = np.array([0])

a_dict = dict()

a_dict[arr[0]] = "X"

print(a_dict)

We can get the elements of an array using the index operator []. Let’s run the code to get the result:

{0: 'X'}

Example #3: Adding a NumPy NDarray to a Set

We can think of a Python set as a dictionary with only keys; therefore, set objects can only contain hashable elements. Let’s look at an example of adding a NumPy array to a set:

import numpy as np

arr = np.array([1, 3, 3, 5, 5, 7, 7])

a_set = set()

a_set.add(arr)

print(a_set)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
      5 a_set = set()
      6 
----≻ 7 a_set.add(arr)

TypeError: unhashable type: 'numpy.ndarray'

The error occurs because the set.add() method adds the array object to the set instead of the array elements.

Solution

To solve this error, we can use the update() method instead of add

import numpy as np

arr = np.array([1, 3, 3, 5, 5, 7, 7])

a_set = set()

a_set.update(arr)

Let’s run the code to see the result:

{1, 3, 5, 7}

Summary

Congratulations on reading to the end of this article! The error: TypeError: unhashable type: ‘numpy.ndarray’ occurs when trying to get the hash value of a NumPy ndarray.

You can add a numpy array directly to a set using the update() method. You cannot add a multi-dimensional ndarray directly to a set, you have to iterate over the ndarray and add each component array to the set using update().

If you want to use the values in a ndarray as keys in a dictionary, you have to extract the values from the array using the indexing operator [].

For further reading on TypeError with unhashable data types, go to the articles:

For further reading on errors involving NumPy, go to the article: How to Solve Python ValueError: all the input arrays must have the same number of dimensions.

Have fun and happy researching!