Unhashable type dict python что за ошибка
Перейти к содержимому

Unhashable type dict python что за ошибка

  • автор:

TypeError: unhashable type: 'dict'

This piece of code is giving me an error unhashable type: dict can anyone explain to me what the solution is?

4 Answers 4

You’re trying to use a dict as a key to another dict or in a set . That does not work because the keys have to be hashable. As a general rule, only immutable objects (strings, integers, floats, frozensets, tuples of immutables) are hashable (though exceptions are possible). So this does not work:

To use a dict as a key you need to turn it into something that may be hashed first. If the dict you wish to use as key consists of only immutable values, you can create a hashable representation of it like this:

Now you may use key as a key in a dict or set :

Of course you need to repeat the exercise whenever you want to look up something using a dict:

If the dict you wish to use as key has values that are themselves dicts and/or lists, you need to recursively «freeze» the prospective key. Here’s a starting point:

How to Fix – TypeError unhashable type ‘dict’

In Python, a TypeError is raised when an operation or function is applied to an object of inappropriate type. One such error is the “TypeError: unhashable type: ‘dict’” error. This error occurs when we try to use a dictionary as a key in another dictionary or as an element in a set. In this tutorial, we will discuss the reasons behind this error and how to fix it.

how to fix typeerror unhashable type

Understanding the TypeError: unhashable type: ‘list’ error

In Python, hashable types are those which have a hash value that remains constant throughout its lifetime. Hash values are unique identifiers assigned to objects by Python’s built-in hash() function. These hash values are used to quickly compare and access objects in dictionaries and sets.

On the other hand, unhashable types are those which do not have a constant hash value and cannot be used as keys in dictionaries or elements in sets. Examples of unhashable types include lists, sets, and dictionaries themselves.

To illustrate the difference between hashable and unhashable types, consider the following example:

In the above example, we create a tuple my_tuple and a dictionary my_dict . When we try to hash the tuple using the built-in hash() function, we get a unique hash value. However, when we try to hash the dictionary, we get a TypeError because dictionary objects are unhashable. This means that we cannot use dictionaries as keys in other dictionaries or elements in sets.

The TypeError: unhashable type: ‘dict’ error occurs when we try to use a dict object in a place that requires a hashable type, for example, as a key to a dictionary or a value in a set. This error occurs because dictionaries are mutable, which means that their contents can be changed. In Python, only immutable objects can be used as keys in a dictionary or as elements in a set. Here are some common scenarios in which this error occurs:

  • When we try to use a dictionary as a key in another dictionary
  • When we try to use a dictionary as an element in a set

In the above example, we’re trying to use the dict address as a key in the dictionary employee_details . You can see that we get the TypeError: unhashable type: ‘dict’ .

In the above example, we’re trying to add the dict my_dict as an element to the set my_set . Since dictionaries are unhashable types, we get the error TypeError: unhashable type: ‘dict’ .

Fixing the Error

To fix the TypeError: unhashable type: ‘dict’ , do not use a dictionary in places that require a hashable type. For example, as a key to another dictionary or as an element in a set.

Let’s revisit the example from above and fix the error.

In the above example, we’re not using a dictionary as a key in the dictionary employee_details instead we are using a string, ‘Address’ (which is hashable type) and setting its value to the dictionary address . Note that you can still use a dictionary as a value in another dictionary but the keys must be hashable types only.

Conclusion

The “TypeError: unhashable type: ‘dict’” error occurs when we try to use a dictionary as a key in another dictionary or as an element in a set. This error can be fixed by using a hashable type instead of a dictionary. By following the steps mentioned in this tutorial, you can easily fix this error and make your code more efficient and error-free.

You might also be interested in –

Author

Piyush Raj

Piyush is a data professional passionate about using data to understand things better and make informed decisions. He has experience working as a Data Scientist in the consulting domain and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects.

About

Data Science Parichay is an educational website offering easy-to-understand tutorials on topics in Data Science with the help of clear and fun examples.

Почему Python выдаёт ошибку unhashable type: ‘dict’?

TosterModerator

Вы пытаетесь в качестве ключа в словаре использовать нехешируемый тип (в данном случае судя по ошибке тоже словарь user_group).
Ключем в словаре может быть только хешируемый тип, например кортеж (без вложенных нехешируемых элементов), строка, число и т.д.

Относитесь, пожалуйста, с уважением к людям на этом ресурсе: оформляйте код тегами и полностью приводите стек-трейс ошибок.

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!

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

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