Open In App

TypeError: unhashable type slice in Python

Last Updated : 02 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

typeError is a common issue in Python that can arise due to various reasons. One specific TypeError that developers might encounter is the “Unhashable Type: ‘Slice'”. This error occurs when you try to use a slice object (created using the colon : notation) as a key in a dictionary or as an element in a set, which is not allowed because slices are mutable and, hence, unhashable. In this article, we will explore the cause of this error and discuss potential solutions to fix it.

What is Typeerror: Unhashable Type: ‘Slice’ in Python?

The error message, “TypeError: Unhashable Type: ‘Slice'”, indicates that you are attempting to use a slice object in a context where a hashable type is expected. Hashable types are those whose values do not change during their lifetime, allowing them to be uniquely identified by their hash value. Slices, being mutable, cannot be hashed, leading to this error.

Reasons for Typeerror: Unhashable Type: ‘Slice’ in Python

Below are the reasons by which Typeerror: Unhashable Type: ‘Slice’ error occurs in Python:

Slicing a Python Dictionary

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 by slicing a dictionary and a list

Python3




# creating a list
 
Number = [1, 2, 3, 4, 5, 6, 7, 8]
print(Number)
 
# slice the list from index 0 to 4, including index 4
print("List sliced from index 0 - 4: ", Number[0:4])
 
# slice the list from index 4 to 8, including index 8
print("List sliced from index 4 - 8: ", Number[4:8])


Output

[1, 2, 3, 4, 5, 6, 7, 8]
List sliced from index 0 - 4:  [1, 2, 3, 4]
List sliced from index 4 - 8:  [5, 6, 7, 8]



Slicing works perfectly with lists because they operate on an index basis. Now, let’s try slicing on dictionaries. We cannot slice dictionaries in Python because they don’t operate on index bases. Instead, they work in a key-value structure. Each pair has a custom key with a specific value against it, and to access the values, you’ll need the corresponding key.

Python3




# creating a dictionary
 
divct = { "One": 1, "Two": 2, "Three": 3, "Four": 4, "Five": 5 }
 
print(divct)
 
# slicing a dictionary
print(divct[1:5])


Hangup (SIGHUP)
Traceback (most recent call last):
  File "Solution.py", line 24, in <module>
    print(d[1:5]) # --> TypeError: unhashable type: 'slice'
TypeError: unhashable type: 'slice'

Including Slice Object Inside the Python Set

In this example, a set is created with two slice objects, `slice(1, 3)` and `slice(4, 6)`, directly included as elements. However, attempting to include unhashable slices in a set raises a `TypeError`.

Python3




my_set = {slice(1, 3), slice(4, 6)}
 
print(my_set)


Output:

Hangup (SIGHUP)
Traceback (most recent call last):
  File "Solution.py", line 1, in <module>
    my_set = {slice(1, 3), slice(4, 6)}
TypeError: unhashable type: 'slice'

Fix Typeerror: Unhashable Type: ‘Slice’ in Python

Below are some of the ways to fix Typeerror: Unhashable Type: ‘Slice’ in Python:

  • Convert Dictionary Items to List
  • Use OrderedDict and islice from itertools
  • Extract Keys and Perform Slicing

Convert Dictionary Items to List

In this approach, we convert the dictionary items to a list, and then perform the slicing operation.

Python3




# Original Dictionary
original_dict = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
 
# Convert dictionary items to a list and then slice
dict_items_list = list(original_dict.items())
sliced_items = dict_items_list[1:3]
 
# Result
print("Original Dictionary:", original_dict)
print("Sliced Items:", dict(sliced_items))


Output

Original Dictionary: {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
Sliced Items: {'b': 2, 'c': 3}



Using OrderedDict and islice from itertools

In this approach, we used OrderedDict to maintain the order of the items and islice from the itertools module to perform slicing.

Python3




from collections import OrderedDict
from itertools import islice
 
# Original Dictionary
original_dict = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
 
# Use OrderedDict and islice for slicing
sliced_dict = dict(islice(OrderedDict(original_dict).items(), 1, 4))
 
# Result
print("Original Dictionary:", original_dict)
print("Sliced Dictionary:", sliced_dict)


Output

Original Dictionary: {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
Sliced Dictionary: {'b': 2, 'c': 3, 'd': 4}



Extract Keys and Perform Slicing

In this approach, we extract the keys of the dictionary, perform slicing on the keys, and then create a new dictionary with the sliced keys.

Python3




# Original Dictionary
original_dict = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
 
# Extract keys, perform slicing, and create a new dictionary
keys = list(original_dict.keys())[1:4]
sliced_dict = {k: original_dict[k] for k in keys}
 
# Result
print("Original Dictionary:", original_dict)
print("Sliced Dictionary:", sliced_dict)


Output

Original Dictionary: {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
Sliced Dictionary: {'b': 2, 'c': 3, 'd': 4}



Conclusion

In this article we studied on how to fix the TypeError unhashable type slice, we have discussed what the “TypeError : unhashable type: ‘slice’” error in Python is and how to resolve it. In addition, we have discussed how to work on a dictionary using the items() and keys() functions.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads