Python TypeError: unhashable type: ‘slice’ Solution

Posted in /  

Python TypeError: unhashable type: ‘slice’ Solution
vinaykhatri

Vinay Khatri
Last updated on November 24, 2024

    Python Dictionaries are the built-in hashtable data structure that maps a key to a corresponding value . It stores all of its elements in the form of key:value pairs. And like a list and tuple, we can square bracket [] syntax to access a dictionary element using its key value.

    But if we try to access a series of elements from a dictionary like a list slicing, we will receive the TypeError: unhashable type: 'slice' Error. Because Python dictionary does not support slicing.

    In this Python error guide, we will walk through the Python TypeError: unhashable type: 'slice' Error statement. And discuss why this error occurs in Python and how to solve it.

    So let's get started with the Error Statement.

    Python Error: TypeError: unhashable type: 'slice'

    The Error Statement TypeError: unhashable type: 'slice' has two parts

    1. Exception Type
    2. Error Message

    1. Exception Type( TypeError )

    TypeError occurs in Python when we try to perform an operation on an unsupported data type object. In this tutorial, we are trying to perform a slicing operation on a dictionary, which is not a valid dictionary operation. That's why we are encountering this error.

    2. Error Message( unhashable type: 'slice' )

    The Error Message unhashable type: 'slice' , is telling us that we are trying to perform slicing on a dictionary object. Dictionary is a washable data structure, and it does not support slicing like string, tuple, and list.

    Error Example

    Slicing is an operation that can slice out a sequential pattern from subscriptable objects like a list , string , and tuple . All these three data structures store elements' characters in sequential order and provide index numbers to each element which makes slicing possible on these objects.

    Example

    string_ = "abcdefg"
    tuple_ = ('a', 'b', 'c', 'd', 'e', 'f', 'g')
    list_ = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
    
    # python string slicing first 3 elements
    print(string_[:3])
    # python tuple slicing first 4 elements
    print(tuple_[:4])
    # python list slicing first 5 elements
    print(list_[:5])

    Output

    abc
    ('a', 'b', 'c', 'd')
    ['a', 'b', 'c', 'd', 'e']

    Python dictionary uses keys as indices for its different values. Although we can use the keys to access individual values from a dictionary, but can not use slicing to access a range of values, like list, tuple, and string. If we try to perform a slicing on a dictionary, we will receive a TypeError, because slicing is not supported by a dictionary-type object.

    Example

    Let's say we have a dictionary rank_board that stores the detail of the first 5 rank holder students. And we only want to print the details of the first 3 students.

    So let's see what happens if we use slicing to access the details of the first 3 students.

    rank_board = {
                'rank1':{'name':'Rahul', 'score':100, 'age':20},
                'rank2':{'name':'Vikas', 'score':99.3, 'age':19},
                'rank3':{'name':'Ankit', 'score':99, 'age':20},
                'rank4':{'name':'Raj', 'score':98.9, 'age':20},
                'rank5':{'name':'Jay', 'score':98.5, 'age':21},
                }
    
    # access first 3 rank holders details
    print(rank_board[0:3])     #error

    Output

    Traceback (most recent call last):
    File "main.py", line 10, in <module>
    print(rank_board[0:3]) #error
    TypeError: unhashable type: 'slice'

    Break the code

    The output error statement is what we expected. In line 10, we tried to access the first 3 elements of the dictionary using slicing syntax rank_board[0:3] , which is invalid for the Python dictionary, that's why we are getting this error.

    Solution

    If you ever encounter a problem where you need to access a series of elements from a dictionary, there you must not use the slicing because the dictionary does not support it.

    The other option you have is using a for loop with zip , and range functions. The zip() function will help you to zip the dictionary keys with the range iterator. And the range() function will help you to specify the number of elements you want to access from the dictionary.

    Example solution

    Now, let's solve the above example using the for loop, zip() , and range() function.

    rank_board = {
                'rank1':{'name':'Rahul', 'score':100, 'age':20},
                'rank2':{'name':'Vikas', 'score':99.3, 'age':19},
                'rank3':{'name':'Ankit', 'score':99, 'age':20},
                'rank4':{'name':'Raj', 'score':98.9, 'age':20},
                'rank5':{'name':'Jay', 'score':98.5, 'age':21},
                }
    
    for _, key in zip(range(3), rank_board):
        print(f"------{key}------")
        print(rank_board[key])

    Output

    ------rank1------
    {'name': 'Rahul', 'score': 100, 'age': 20}
    ------rank2------
    {'name': 'Vikas', 'score': 99.3, 'age': 19}
    ------rank3------
    {'name': 'Ankit', 'score': 99, 'age': 20}

    Break the code

    In the above example, using the zip(range(3), rank_board) , we zip 0 to 3 range iterator with the first 3 keys of the rank_board dictionary. And using the for loop, we access those three keys and their corresponding values.

    Wrapping Up!

    Python dictionary is not like a list, tuple, or string. It is a more advanced Python data structure and does not support normal indexing using integer values. To access dictionary elements, we can use the key as an index value for the corresponding value. And like list and tuple dictionary do not support slicing and throw the  TypeError: unhashable type: ‘slice’ error if tried.

    To access the dictionary elements, we need the keys, and only one value of a dictionary can be accessed using one key.

    If you are still getting this error in your Python program, you can share your code in the comment section. We will try to help you in debugging.

    People are also reading:

    Leave a Comment on this Post

    0 Comments