Typeerror: unhashable type: ‘slice’

One of the errors you might face when working with Python dictionaries and pandas DataFrames is Typeerror: unhashable type: ‘slice’.

This error occurs for two main possible reasons:

  1. Trying to slice dictionary object.
  2. Trying to slice Dataframe object.

So in this guide, we will tackle possible solutions to fix this error, as well as practical example codes for better understanding.

What is Typeerror: unhashable type: ‘slice’?

TypeError: unhashable type: ‘slice’ is an error that occurs when you try to use a slice object as a key in a Python dictionary or set.

Additionally, if you’re working with a pandas DataFrame object, this error can occur when you try to encode categorical data using scikit-learn’s LabelEncoder.

Furthermore, a slice object in Python is an index that refers to a range of elements in a sequence, such as a string or a list.

However, slice objects are considered unhashable, which means they cannot be used as keys in dictionaries or sets because they do not have a fixed hash value.

Why this unhashable type slice error occur?

The “TypeError: unhashable type: ‘slice'” error occurs with the following possible scenarios:

  • Using a slice object as a key in a dictionary or set
  • Trying to modify a slice object
  • Passing a slice object to a function that expects a hashable object
  • Trying to compare slice objects with the ‘is’ operator

How to fix this typeerror unhashable type ‘slice’

Since we encounter TypeError: unhashable type: ‘slice’ when we are…

  1. slicing a dictionary object or;
  2. encoding categorical data stored in a DataFrame

This time we will present the solution of each scenario why we encounter this error.

Scenario 1: Slicing a dictionary object

This time, we have an example of how this error occurs when we try to slice a dictionary.

samp_dict = {
    'id': 1,
    'name': 'it sourcecode',
    'age': 17,
}

# TypeError: unhashable type: 'slice'
print(samp_dict[:2])

Output:

Traceback (most recent call last):
  File "C:\Users\Windows\PycharmProjects\pythonProject1\main.py", line 8, in <module>
    print(samp_dict[:2])
TypeError: unhashable type: 'slice'

As you can see the output throws an error because we can’t slice a dictionary.

To fix this error we need to manually access key-value pairs.

Wherein we can access specific key-value pairs by using bracket notation.

Here is the example code:

a_dict = {
    'id': 1,
    'name': 'It Sourcecode',
    'age': 17,
}

a_slice = list(a_dict.items())[:2]

print(a_slice)

for key, value in a_slice:
    print(key, value)

The code above produces the following output:

[(‘id’, 1), (‘name’, ‘It Sourcecode’)]
id 1
name It Sourcecode

Items() method in slicing Dictionary

Another way to slice a dictionary is using items() method.

a_dict = {
    'id': 1,
    'name': 'it sourcecode',
    'age': 17,
}

a_slice = list(a_dict.items())[:2]

print(a_slice)

for key, value in a_slice:
    print(key, value)

Be aware that we convert the dictionary using list() class before we slice the dictionary.

This is necessary because the dict_items object cannot directly be sliced.

my_dict = {'id': 1,  'name': 'It soourcecode'}
print(my_dict.items())

Output:

dict_items([(‘id’, 1), (‘name’, ‘It soourcecode’)])

Meanwhile, use a for loop to iterate over a slice of the dictionary.

a_dict = {
    'id': 1,
    'name': 'it sourcecode',
    'age': 17,
}

a_slice = list(a_dict.items())[:2]

for key, value in a_slice:
    print(key, value)

Output:

id 1
name it sourcecode

Scenario 2: Encoding categorical data stored in a DataFrame

As already mentioned an error can occur when we are working with pandas DataFrame object. Particularly, when we are trying to encode categorical data using scikit-learn’s LabelEncoder.

Suppose we have DataFrame has one categorical data column named Name:

import pandas as pd

df = pd.DataFrame({
        "Name": ["Bem", "Ben", "Bet", "Ber"],
        "age": [20, 26, 30, 40],
        "salary": [10000, 90232, 67456, 55522],
        "Claim": ["yes", "no", "yes", "no"],
    })

Then we use slicing syntax with the DataFrame object, when we want to encode Name column as follows:

from sklearn.preprocessing import LabelEncoder

labelencoder_X = LabelEncoder()
df[:, 0] = labelencoder_X.fit_transform(df.iloc[:, 0])

What we highlighted line above will raise an error. It is not because of fit_transform method, but because we can not use slicing syntax in assigning new values to a DataFrame object.

Traceback (most recent call last):
File “main.py”, line 15, in <module>
df[:, 0] = labelencoder_X.fit_transform(df.iloc[:, 0])
TypeError: unhashable type: ‘slice’

Meanwhile, the right method should be the iloc() method or the column name as presented below:

df.iloc[:, 0] = labelencoder_X.fit_transform(df.iloc[:, 0])

# or
df['Name'] = labelencoder_X.fit_transform(df['country'])

The same as the dictionaries case we cannot assign new values to a DataFrame column when using slicing syntax.

Keep in mind that we need to use to iloc() method or pass the column name directly inside the square brackets.

Anyhow, if you are finding solutions to some errors you might encounter we also have TypeError can’t concat str to bytes.

Conclusion

In conclusion, Typeerror: unhashable type: ‘slice’ we covered occurs when we try to slice a dictionary object or encoding categorical data stored in a DataFrame.

To fix this error we need to convert the dictionary’s items to a list before slicing. Thus, when it is DataFrame object we use iloc() method before slicing it.

We hope you have learned in this guide and have helped you fix the error.

Thank you for reading.

Frequently Asked Questions (FAQs)

How do you fix Unhashable type slice?

The “Unhashable type slice” error typically occurs when trying to use a list or slice (i.e., a portion of a list) as a key for a dictionary or an element in a set.

To fix this error, you can convert the list or slice to a tuple, which is immutable and can be hashed.

What does unhashable type mean?

In Python, a hashable object is one that can be converted to a unique integer value, which is used to identify the object and can be used as a key in a dictionary or an element in a set.