Python

Resolved “TypeError: Unhashable Type” Numpy.Ndarray

Errors are the bread and butter in every programmer’s life. You will run into errors no matter what language, tool, or project you are working on. When working with Python, one error you may encounter is the “TypeError: unhashable type” error. Using this guide, we will understand why this error happens and what we can do to fix it in our code.

Python Hashable

We first need to understand Python’s hashable objects before resolving this error. In Python, a hashable object refers to an object whose value does not change once defined and can be represented as a unique hash value using the hash() function. Although very relatable, hashable does not necessarily mean that the object is immutable. This means that every immutable object in Python is hashable, but not all hashable objects are immutable.

Examples of mutable objects in Python include int, floats, str, and tuples. Other types, such as dictionaries, sets, and lists, are unhashable.

Python Check Hashable

Python provides us with the hash() function to check if an object is hashable.

For example:

# check if hashable
print(hash('linuxhint'))

We use the hash() function with a string object in the above snippet. If the provided object is hashable, the function should return a unique hash value as shown:

-2672783941716432156

However, if we run the hash() function with an unhashable type, the “TypeError: unhashable type:” error is generated.

An example is as shown in the code below:

print(hash({'key': 'value'}))

Since a Python dictionary is unhashable, the code above should return the error as shown:

TypeError: unhashable type: ‘numpy.ndarray’

There are three main scenarios where we can get this error in NumPy. These include:

  1. Using a NumPy array as a key to a Python dictionary.
  2. Adding a NumPy array to a set
  3. Conversion of N-dimensional array to a set.

Using NumPy Array as a Key

Only hashable objects can be used as keys to a dictionary in Python. Since a NumPy ndarray is not hashable, any attempt to use it as a key in a dictionary will result in an error.

This is illustrated as shown:

import numpy as np
arr = np.array([1,2,3])
dict = {arr: 'value'}

In this example, we attempt to use a NumPy array as a key to a dictionary. This results in the error as shown below:

We can convert the data type to a hashable object to fix this. In our case, converting the array into a set makes more sense.

arr = np.array([1,2,3])
# convert to tuple
tup = tuple(arr)
# set tuple as key
dict = {tup: 'value'}
print(dict)

We convert the ndarray to a tuple and assign it as the key.

Adding a NumPy Array to a Set

Attempting to add a ndarray to a set will also result in this error. An example is as shown:

arr = np.array([1,2,3])
s = set()
s.add(arr)

We are attempting to add a ndarray to a set in this case. Therefore, the code above should return an error:

We can solve this by adding each array element instead of the array object into the set.

arr = np.array([1,2,3])
s = set()
for i in arr:
    s.add(i)
print(s)

This should add all the elements of the array to the set.

{1, 2, 3}

N-Dimension Conversion to Set

Another instance where this error may occur is converting an N-dimension array to a set.

Example:

arr = np.array([[1,2,3], [4,5,6]])
s = set(arr)
print(s)

The code above converts a 2D array to a set. Similarly, the code above will result in an error as shown:

You can solve this error by accessing the elements of the array individually.

Solved

This article covered the ” TypeError: unhashable type:” error in Python, why it occurs, and how to fix it in our NumPy code.

See you at the next one!!

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list