[Solved] TypeError: Unhashable Type: ‘slice’

In this article we will we looking the Python exception TypeError: Unhashable Type: ‘slice’. Python dictionaries store their data in key-value format. Since Python 3.7 dictionaries are considered ordered data.

Index values are not assigned to dictionaries. Therefore, any operation that involves index values like slicing will throw the said exception.

Let’s look at the exception in detail

What is a TypeError?

Any invalid operations performed on a data type object will cause TypeErrors. For example, using the addition operator (+) between a string type and an integer. The common causes for TypeErrors are:
Unsupported operation between two types
Incorrect type of list index
Calling a non-callable identifier
Iterating through a non-iterative identifier

What is an Unhashable Type?

Hash values are used in place of index values for dictionary elements.  Python compares dictionary keys with hash values while working with dictionary elements. We can hash strings or integers but cannot slice them. A slice is nothing but a small subset of a sequential type. It usually consists of a small portion from a bigger data sequence. As slice values are unhashable, any attempts to slice hashed types raise said exception.

What Causes this Error?

Any slice operations on a dictionary object will give rise to this error. A Python Dictionary is a hashable type and does not support slicing like other sequential data types.

Let’s look at the following example:

myCompany = {
            'employee1':{'name':'Adam', 'ID':230001, 'role':'Developer'},
            'employee2':{'name':'Mike', 'ID':230002, 'role':'Developer'},
            'employee3':{'name':'Joe', 'ID':230003, 'role':'Developer'},
            'employee4':{'name':'Chris', 'ID':230004, 'role':'Developer'},
            'employee5':{'name':'Frank', 'ID':230005, 'role':'Developer'}
            }

showEmployee = myCompany[:3]
print(showEmployee)

Output

unhashable type: 'slice'
unhashable type: ‘slice’

Solution

Using the print() statement and the dictionary keys, we can display the contents of the dictionary.

myCompany = {
            'employee1':{'name':'Adam', 'ID':230001, 'role':'Developer'},
            'employee2':{'name':'Mike', 'ID':230002, 'role':'Developer'},
            'employee3':{'name':'Joe', 'ID':230003, 'role':'Developer'},
            'employee4':{'name':'Chris', 'ID':230004, 'role':'Developer'},
            'employee5':{'name':'Frank', 'ID':230005, 'role':'Developer'}
            }

print("Employee 1 " + myCompany["employee1"])
print("Employee 2 " + myCompany["employee2"])
print("Employee 3" + myCompany["employee3"])

TypeError: Unhashable Type: ‘slice’ for Pandas Data Frames

The below code demonstrates how we can print a subset of rows in a pandas data frame.

print(sample_data[25:150, :])
print(sample_data[100:300, :].shape)

Error Output

TypeError: unhashable type: 'slice'

Solution

.iloc() function allows indexing in pandas data frames. .iloc() function is similar to normal indexing, except that its indices are based on position.

print(sample_data.iloc[25:1150, :])
print(sample_data.iloc[100:300, :].shape)

TypeError: Unhashable Type: ‘slice’ for JSON

Let’s refer to the following implementation. An API request is sent data is fetched in JSON format.

import requests
import json

req = requests.get('http://sampleAPI.net/sample)
date = json.loads(req.text)
data = req.json()

for i in data['myItem'][:3]:
  res = i['attribute']
  print(res)

Output

TypeError: unhashable type: 'slice' error

Solution

myItem seems to be of type Dictionary. Therefore, any attempt at indexing will throw the exception. It’s better to use the .items() function.

import requests
import json

req = requests.get('http://sampleAPI.net/sample)
date = json.loads(req.text)
data = req.json()

for i in data(['myItem'].items())[:3]:
  res = i['attribute']
  print(res)

TypeError: Unhashable Type: ‘slice’ for Beautiful Soup Module

The BeautifulSoup module is used for web scraping data from HTML and XML sources. Let’s look at the following implementation that scrapes text data from a website.

import requests
from bs4 import BeautifulSoup

r = requests.get('https://samplewebsite.com/samplePage01')
soup = BeautifulSoup(r.text, 'html.parser')
results = soup.find_all('td', attrs={'valign':'top'})

records = []
for result in results:
    name = result.contents[0][0:-1]

Output

TypeError: unhashable type: 'slice' error

Solution

.contents consist of tag objects. Therefore an exception is thrown when accessing a tag attributes dictionary.

Furthermore, using .strings allows you to fetch only NavigableString data.

for result in results:
    name = list(result.strings)[0][0:-1]

TypeError: Unhashable Type res = cache.get(item)

Let’s look at the following implementation for a “Random Forest” model.

import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score
from sklearn.metrics import confusion_matrix
import sklearn
import sklearn.datasets
import sklearn.ensemble
import numpy as np
import lime
import lime.lime_tabular

class Randomforest:

    def __init__(self):
        self.trained_model = None
        self.clf = None
        pass

...
...
...
...

    rf = Randomforest()

...
...
...
...

    dataset = pd.read_csv("filename.csv")

    train_x, test_x, train_y, test_y = rf.split_dataset(dataset, 0.7, Headers[1:-1], Headers[-1])

    trained_model = rf.random_forest_classifier(train_x, train_y)

    predictions = trained_model.predict(test_x)

    feature_names = Headers[1:-1]

    class_names = ['1', '0']

    explainer = lime.lime_tabular.LimeTabularExplainer(train_x, feature_names= feature_names, class_names=class_names,
                                                   categorical_features= None, categorical_names=None, discretize_continuous=True,
                                                   kernel_width=3)

Output

TypeError: Unhashable Type

Solution

We are passing the training data (train_x) into the model as a pandas data frame. Pandas do not allow slice operations on data frames. Hence, pass train_x as train_x.values.

FAQs on TypeError: Unhashable Type: ‘slice’

How are TypeErrors caused?

TypeErrors are one of Python’s many exceptions types. ¬†Operations performed on unsupported object types cause the error. The common causes for TypeErrors are:
Unsupported operation between two types
Incorrect type of list index
Calling a non-callable identifier
Iterating through a non-iterative identifier

What are the sliceable Objects?

Sliceable objects in Python include:
– Strings
– Bytes
Tuples
– Lists

A sliceable object must support indexing. Hashable data types are not sliceable.

Conclusion

Indexing on dictionary types and other hashable data types gives rise to the error.

The main reasons for TypeErrors are:

  1. Unsupported operation between two types
  2. The incorrect type of list index
  3. Calling a non-callable identifier
  4. Iterating through a non-iterative identifier

A more convenient way to access dictionary elements is to provide the key value. An iteration may be provided to access multiple dictionary elements at a time.

Therefore, we have demonstrated various instances where the error may take place.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments