Unhashable type dict что значит

Как решить ошибку “unhashable type: list” в Python

Привет гики и добро пожаловать в этой статье мы будем освещать “unhashable type: list”. Это тип ошибки, с которой мы сталкиваемся при написании кода

Автор: Team Python Pool
Дата записи

Как решить ошибку “unhashable type: list” в Python

Привет гики и добро пожаловать. В этой статье мы рассмотрим ошибку “unhashable type: list.” С этой ошибкой мы сталкиваемся при написании кода на Python. В этой статье наша главная цель – рассмотреть эту ошибку и устранить её. Всего этого мы добьемся на нескольких примерах. Но сначала давайте попробуем получить краткий обзор того, почему она возникает.

Читайте также:  Что значит испепеляющий взгляд

Словари Python принимают в качестве ключа только хэшируемые типы данных. Это означает что значения этих типов остаются неизменными в течение всего их времени жизни. Но когда мы используем тип данных list, который не является хэшируемым, мы получаем такую ошибку.

Ошибка “unhashable type: list”

В этом разделе мы рассмотрим причину, из-за которой возникает эта ошибка. Мы учтем все, что обсуждалось до сих пор. Давайте рассмотрим это на примере:

Выход:

Выше мы рассмотрели простой пример. Мы создали числовой словарь, а затем попытались распечатать его. Но вместо вывода мы получаем ошибку, потому что использовали в нем тип list в качестве ключа. В следующем разделе мы рассмотрим, как устранить эту ошибку.

Но прежде давайте рассмотрим еще один пример.

В приведенном выше примере мы сталкиваемся всё с той же проблемой. В этом словаре мы взяли в качестве данных количество государств и их рейтинг по всему миру. Теперь давайте быстро перейдем к следующему разделу и устраним эти ошибки.

Устранение ошибки “unhashable type:list”

В этом разделе мы постараемся избавиться от ошибки. Давайте начнем с первого примера. Чтобы исправить все это, мы должны использовать кортеж.

С помощью всего лишь небольшого изменения кода мы можем исправить ошибку. Здесь мы использовали кортеж, который является неизменяемым (hashable) типом данных. Аналогично мы можем исправить ошибку во втором примере.

Опять же с помощью кортежа мы можем всё исправить. Это простая ошибка, и ее легко исправить.

Разница между hashable и unhashable типами данных

В этом разделе мы видим основное различие между двумя типами. Кроме того, мы классифицируем различные типы данных, которые мы используем при кодировании на python, под этими 2 типами.

В этом разделе мы видим основное различие между двумя типами данных. Кроме того, мы классифицируем различные типы данных, которые мы используем при кодировании в Python под этими двумя типами.

Хэшируемые Нехэшируемые
Для этого типа данных значение остается постоянным на всем протяжении жизни объекта. Для этого типа данных значение не является постоянным и изменяется по месту.
Типы данных, подпадающие под эту категорию: int, float, tuple, bool, string, bytes. Типы данных, подпадающие под эту категорию: list, set, dict, bytearray.

Заключение

В этой статье мы рассмотрели ошибку unhashable type: list. Мы рассмотрели, почему она возникает, и методы, с помощью которых мы можем её исправить. Чтобы разобраться в этом, мы рассмотрели несколько примеров. В конце концов, мы можем сделать вывод, что эта ошибка возникает, когда мы используем нехэшируемый (изменяемый) тип данных в словаре.

Источник

Unhashable Type Python Error Explained: How To Fix It

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 dictionary.

This error can occur in multiple scenarios and in this tutorial we will analyse few of them to make sure you know what to do when you see this error.

Let’s fix it now!

Unhashable Type ‘Dict’ Python Error

To understand when this error occurs let’s replicate it in the Python shell.

We will start from a dictionary that contains one key:

Now add a second item to the dictionary:

All good so far, but here is what happens if by mistake we use another dictionary as key:

The error unhashable type: ‘dict’ occurs because we are trying to use a dictionary as key of a dictionary item. By definition a dictionary key needs to be hashable.

What does it mean?

When we add a new key / value pair to a dictionary, the Python interpreter generates a hash of the key. To give you an idea of how a hash looks like let’s have a look at what the hash() function returns.

You can see that we got back a hash for a string but when we tried to pass a dictionary to the hash function we got back the same “unhashable type” error we have seen before.

The unhashable type: ‘dict’ error is caused by the fact that mutable objects like dictionaries are not hashable.

Unhashable Type ‘numpy.ndarray’ Python Error

Let’s have a look at a similar error but this time for a numpy.ndarray (N-dimensional array).

After defining an array using NumPy, let’s find out what happens if we try to convert the array into a set.

We see the “unhashable type” error again, I want to confirm if once again we see the same behaviour when we try to apply the hash() function to our ndarray.

The error is exactly the same, but why are we seeing this error when converting the array into a set?

Let’s try something else…

The array we have defined before was bi-dimensional, now we will do the same test with a uni-dimensional array.

It worked this time.

The reason why the first conversion to a set has failed is that we were trying to create a set of NumPy arrays but a NumPy array is mutable and hence it cannot be used as element of a set.

The items in a set have to be hashable. Only immutable types are hashable while mutable types like NumPy arrays are not hashable because they could change and break the lookup based on the hashing algorithm.

For example, strings are immutable so an array of strings should get converted to a set without any errors:

All good. The same behaviour we have seen also applies to normal Python lists instead of NumPy arrays.

Unhashable Type ‘Slice’ Error in Python

The error unhashable type: ‘slice’ occurs if you try to use the slice operator with a data type that doesn’t support it.

For example, you can use the slice operator to get a slice of a Python list.

But what happens if you apply the slice operator to a dictionary?

The slice works on indexes and that’s why it works on lists and it doesn’t work on dictionaries.

Dictionaries are made of key-value pairs and this allows to access any value by simply using the associated dictionary key.

Unhashable Type ‘List’ in Python

Here is when you can get the unhashable type ‘list’ error in Python…

Let’s create a set of numbers:

All good so far, but what happens if one of the elements in the set is a list?

We get back the unhashable type error, and that’s because…

The items of a Python set have to be immutable but a list is mutable. This is required because the items of a set need to be hashable and a mutable data type is not hashable considering that its value can change at any time.

The tuple is similar to a list but is immutable, let’s see if we can create a set a provide a tuple instead of a list as one of its items:

No error this time.

The difference between a list and a tuple in Python is that a list is mutable, is enclosed in square brackets [ ] and is not hashable. A tuple is immutable, is enclosed in parentheses () and is hashable.

Unhashable Type ‘Set’ Python Error

It’s time to find out how you can also encounter the unhashable type error when trying to use a set as item of another set.

First of all let’s define a list of sets:

It works fine because the elements of a list can be mutable.

Now, instead of defining a list of sets we will try to define a set of sets.

Start by creating an empty set:

Then we will use the set add method to add a first item of type set to it.

We get back the error unhashable type: ‘set’ because, as explained before, the items of a set have to be immutable and hashable (e.g. strings, integers, tuples).

As a workaround we can use a different datatype provided by Python: the frozenset.

The frozenset is an immutable version of the Python set data type.

Let’s convert the item set to a frozenset:

And now add the frozenset to the empty set we have defined before:

Hash Function For Different Data Types

We have seen that the unhashable type error occurs when we use a data type that doesn’t support hashing inside a data structure that requires hashing (e.g. inside a set or as a dictionary key).

Let’s go through several Python data types to verify which ones are hashable (they provide a __hash__ method).

Mutable data types are not hashable: list, set, dictionary.

As you can see above, all three data types don’t provide the __hash__ method (None returned).

Immutable data types are hashable: string, integer, float, tuple, frozenset.

All these data types have an implementation of the __hash__ function, they are hashable.

Conclusion

We have seen several circumstances in which the unhashable type error can occur in your Python code.

Specific Python data types require hashable data, for example the items of a set have to be hashable or the keys of a Python dictionary have to be hashable.

If unhashable data is used where hashable data is required the unhashable type error is raised by the Python interpreter.

You now know how to find out the cause of the error and how to solve it potentially by replacing a Python data type that is unhashable with a data type that is hashable.

Источник

Python TypeError: unhashable type: ‘dict’ Solution

The Python language is specific about what can be used as a key in a dictionary. In a Python dictionary, all keys must be hashable.

    Career Karma matches you with top tech bootcamps Get exclusive scholarships and prep courses

    Career Karma matches you with top tech bootcamps Get exclusive scholarships and prep courses

If you try to use an unhashable key type when adding a key to a dictionary, you’ll encounter the “TypeError: unhashable type: ‘dict’” error.

In this guide, we talk about what this error means and why it is raised. We walk through an example of this error so you can learn how to solve it in your code.

TypeError: unhashable type: ‘dict’

Dictionaries consist of two parts: keys and values. Keys are the identifiers that are bound to a value. When you reference a key, you’ll be able to retrieve the value associated with that key.

Only hashable objects can be keys in a dictionary. Immutable objects such as strings, integers, tuples, and frozensets are hashable, with some exceptions. Dictionaries, therefore, cannot be used as a key in a dictionary.

To add an item to a dictionary, you must specify a valid hashable key. For instance, “name” is a valid key, but < “name”: “test” >is not.

An Example Scenario

Here, we write a program that adds all the cakes that have been sold more than five times at a bakery from one dictionary to another dictionary.

Start by declaring a list of cakes which contains dictionaries about each cake. We also define a dictionary in which we can store the cakes that have been sold more than five times.

81% of participants stated they felt more confident about their tech job prospects after attending a bootcamp. Get matched to a bootcamp today.

Find Your Bootcamp Match

The average bootcamp grad spent less than six months in career transition, from starting a bootcamp to finding their first job.

Start your career switch today

Our “cakes” list contains three dictionaries. Each dictionary contains two keys and values. The key names are “cake” and “sold”.

Now, we write a for loop that goes through our list of cakes and finds the ones that have been sold more than five times. Those cakes will be added to the “sold_more_than_five” dictionary:

In our for loop, we compare whether the value of “sold” in each dictionary is greater than 5. If it is, that item is added to our “sold_more_than_five” dictionary. Then, a message is printed to the console informing the user that the particular cake has been sold more than five times.

Once our loop has run, we print the “sold_more_than_five” dictionary to the console.

Run our code to make sure our program works:

Our code returns an error.

The Solution

Our code does not work because we are trying to create a dictionary key using another dictionary.

Источник

Pandas TypeError: unhashable type: ‘list’/’dict’

Have you tried to work with Pandas, but got errors like:

TypeError: unhashable type: ‘list’

TypeError: unhashable type: ‘dict’

The problem is that a list/dict can’t be used as the key in a dict, since dict keys need to be immutable and unique.

If so, I’ll show you the steps — how to investigate the errors and possible solution depending on the reason. In this article we are working with simple Pandas DataFrame like:

col1 col2 col3
0 1 [0.5, 0.1]
1 2 [0.75, 0.25]

Step #1: TypeError: unhashable type: ‘list’/’dict’

The errors is common for operations like:

when these operations are applied against column of type: ‘dict’ or ‘list’.

Examples for the above DataFrame:

For the last examples there are issues in Pandas:

Step #2: How to detect if column contains list or dict

The first step when the error appears is to identify the columns and what is stored inside. If we try to use the basic df.dtypes this won’t give proper results — whether the column is list, dict or string:

So in order to identify the correct types stored in those columns we need to do something else. For example check which of all columns in a DataFrame have list values inside we can do::

And for dicts we can do:

What about to test column is it list or dict? In this case we can combine both in:

So we will have as result:

When the problematic columns/data is identified we can continue with applying of the next solutions.

Step #3: Convert the column to string and apply value_counts

The first and the most basic solution would be to convert the column to string and apply the operation like: value_counts or groupby :

This will give results for the column as single entities. If you want to get the counts for the elements inside the list then you can check this video: Pandas count values in a column of type list.

Note: It’s really important that you are able to distinguish:

  • column which contains list stored as string
  • column which contains list stored as list
    and the operations which can be applied on them. In the bonus step we will see these difference when we try to expand column!

The same error and solution are visible for groupby :

while this will work:

col1 col3
col2
[0.5, 0.1] 1 1
[0.75, 0.25] 1 1

Step #4: Convert list/dict column to tuple

Another possible solution is first to convert the list/dict columns to tuple and apply the operations on it. For this solution it’s important to note that results differ for list and dict as shown below:

while for dict only the keys will be part of the final result:

Step #5: Expand the list column

Another possible solution is to expand the list column. The column should contain list stored as a list and not as a string. Otherwise the output will be unexpected:

Step #6: List column mixed: strings and list items

Sometimes the columns will have mixed values — for example: numbers, strings and lists. Alternative solution for this case is apply — check each value and convert the values — for example extract the item stored as list. So this time we will work with this DataFrame:

and we will get the first element of a list or we will keep the values as they are:

this will result in:

Bonus Step #1: Correct way to expand list column

One common mistake for Pandas and newbies is applying operation on incorrect data type. Let check an example for using str.split on DataFrame column list. Some will expect the column to be expanded into several columns based on the split:

but actually this will product:

And the problem is that we are trying to apply string operation on list values. We might think that simply converting the list column to string will solve the problem:

but this will add brackets to first and last cell like(which is not best option):

Источник

Оцените статью