Unhashable type slice python что это
Перейти к содержимому

Unhashable type slice python что это

  • автор:

Unhashable Type Python Error Explained: How To Fix It — Codefather

Claudio Sabato

Have you ever seen the message “TypeError: unhashable type” when running your Python program? Do you know what to do to fix it?

The message “TypeError: unhashable type” appears in a Python program when you try to use a data type that is not hashable in a place in your code that requires hashable data. For example, as an item of a set or as a key of a

Claudio Sabato

Written by Claudio Sabato

I’m a Software Engineer and Programming Coach. I want to help you in your journey to become a Super Developer!

How to fix TypeError: unhashable type: 'slice'

When working with Python dictionaries and pandas DataFrames, you might get the following error:

This error occurs when you try to access a dictionary object using a slice. There are two possible reasons why this error happens:

  1. You try to slice a dictionary object
  2. You try to encode categorical data stored in a DataFrame

The following tutorial shows how to fix this error in both scenarios.

1. Slicing a dictionary object

Suppose you have a dictionary object as follows:

Next, you want to create a slice of this dictionary by assigning the first two key-value pairs to a new variable:

But because a dictionary can’t be sliced like a list, you get this error:

The error happens because you can’t slice a dictionary, but it’s also confusing because Python assumes the slice is the key value.

This ambiguity occurs because the syntax to add a new key-value pair to a dictionary is the same as accessing one. If you switch the assignment a bit, it starts to make sense:

If you’re adding a new key-value pair to a dictionary, then the error makes sense because you can’t specify a slice as the key in a dictionary object. You can only use hashable types like str or int .

But when you try to slice a dictionary, the error message is not so intuitive, so it doesn’t help you to understand what’s wrong. A better error message might be “Can’t slice a dictionary object.”

To resolve this error, you need to access a dictionary values using the keys like this:

You can’t use a slicing syntax to get some of key-value pairs from a dictionary because that’s not how a dictionary is designed.

You can only slice sequences like a string, a list, or a tuple in Python.

2. Encoding categorical data in pandas DataFrame

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 .

The following DataFrame has one categorical data column named country :

You want to encode the country column, so you use the slicing syntax with the DataFrame object:

The highlighted line above causes the error:

The error is not because of the fit_transform method, but because you can’t use slicing syntax to assign new values to a DataFrame object.

The right approach is to use the iloc() method or the column name as shown below:

Just like with dictionaries, you can’t assign new values to a DataFrame column using the slicing syntax.

You need to use the iloc() method or pass the column name directly inside the square brackets.

Now you’ve learned how to fix the error unhashable type: 'slice' . Until next time! ��

Get 100 Python Snippets Book for FREE ��

100 Python snippets that you can use in various scenarios

Save 1000+ hours of research and 10x your productivity

About

Sebhastian is a site that makes learning programming easy with its step-by-step, beginner-friendly tutorials.
Learn JavaScript and other programming languages with clear examples.

Free Code Snippets Book

Get my FREE code snippets Book to 10x your productivity here

Ezoic

report this ad

Python TypeError: unhashable type: ‘slice’ Solution

Python TypeError: unhashable type: ‘slice’ Solution

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

Output

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.

Output

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.

Output

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.

Python: TypeError: unhashable type: 'slice'

X and test_X should contain the value from column 4 to last column of the CSV.

May I know what’s wrong with my code and how can I fix this issue?

2 Answers 2

I can see you have resolved your issue, but I thought I’d leave an answer here for any future readers. Who might get caught by this (I just was).

The issue is that the object is a dictionary and you are trying to pass it a slice, which is not hashable and hence cant be used as a dict key.

What you are trying to do is take n items from the collection. So the way to achieve this is to first convert the dict to a list (which is sliceable). To do this use dict.items , dict.keys or dict.values depending on your use case.

A dict (recent python 3.6 development notwithstanding) is not ordered and so what you will get back from dict.items (or friends) may not be in an order useful to you. So you can sort it before making the slice.

The above code is slightly ugly, but works.

You could avoid the indexing by using islice from itertools

You’d provide a key to sort if the default sorting order was not what you wanted. This way is inefficient as it sorts the entire collection before slicing, not sure of a way around that though.

Anyone arriving at this page and being puzzled by the above error, will not have realised they are attempting a slice on a dictionary. Performing a slice on a dictionary, doesn’t really make a lot of sense and most experienced developers would realise that if you do that you are asking for an unpredictable result.

If you genuinely do want to take the first n elements from a dictionary, say a row from a csv file where the columns are in some prescribed order. It would be much better to format the required keys into a tuple and just take those elements from the dict.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *