TypeError unhashable type: ‘dict’
Здравствуйте, возникла проблема с Django не могу никак вывести данные из бд (mysql в таблицу), возникает следующая ошибка:
Exception Value: unhashable type: ‘dict’
Данные пытаюсь получить следующим образом:
кусочек views.py:
List_of_date=El.objects.all() return HttpResponse(template.render(context),args, {'List_of_date': List_of_date})
косочек models.py:
from django.db import models
1 2 3
class El(models.Model): id_ch=models.IntegerField() TXT = models.CharField(max_length=200)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
table> thead> tr> th>№/th> th>Текст/th> /tr> /thead> tbody> tr> td class="center">>/td> td class="center">>/td> /tr> /tbody> /table>
Может кто-нибудь сталкивался с такой проблемой и сможет указать мне путь к решению?
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
Ответы с готовыми решениями:
Ошибка «TypeError: Object of type coroutine is not JSON serializable»
Имеется код: class sensorreadings(Resource): async def get(self): data =.

TypeError: unhashable type: ‘set’
a = int(input()) o = set() g = set() for i in range(a): b = set(input().split()) c =.
TypeError: unhashable type: ‘dict_items’
import datetime datetime def gift_count(budget,month,birthdays): list_birthdays = .
TypeError: an integer is required (got type dict)
Здравствуйте! Код выполняется в консоли iPython. from datetime import date Years =.
![]()
4615 / 2036 / 359
Регистрация: 17.03.2012
Сообщений: 10,102
Записей в блоге: 6
Видимо, пытаетесь использовать словарь в качестве ключа для словаря. Конкретно сложно сказать.
Регистрация: 11.04.2013
Сообщений: 41
Может тогда есть другой способ вывести данные в таблице? Просто когда я искал в гугле постоянно натыкался на эту реализацию.
528 / 431 / 159
Регистрация: 25.11.2014
Сообщений: 1,662
Сообщение от Иван Парамонов 
List_of_date=El.objects.all()
return HttpResponse(template.render(context),args, )
Давно с Django не работал. Насколько я помню, у тебя же шаблон должен рендериться и знать о твоих переменных, а не HttpResponse, почему ты словарь <'List_of_date': List_of_date>отдаешь отдаешь его конструктору, когда у тебя шаблон — это template? Создай ему контекст с нужными переменными. А не HttpResponse.'List_of_date':>
Регистрация: 11.04.2013
Сообщений: 41
Немогу понять что значит создать контекст с нужными переменными вы предлагаете context=List_of_date?
Я в Django новичок, но насколько я понял вариант с HttpResponse тоже работает ведь я могу передавать переменные через args. К примеру так:
1 2 3
args={} args['TMP']="Temp" return HttpResponse(template.render(context),args)
А в шаблоне его получать через <>
Кроме того такой вариант возврата шаблона я видел в официальной документации и он работает. Но почему то когда я пытаюсь вывести List_of_date то получаю ошибку.
2740 / 2339 / 620
Регистрация: 19.03.2012
Сообщений: 8,830
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
Помогаю со студенческими работами здесь
unhashable type — не могу разобраться
Вот собственно часть задачи. При запуске выводится отчет об ошибке. Помогите найти как исправить.

TypeError: unsupported operand type(s) for *: ‘int’ and ‘type’
Подскажите что за ошибка? TypeError: unsupported operand type(s) for *: ‘int’ and ‘type’ import.

Порядок вывода значений dict при использовании метода dict.values()
Интересует, на всех ли машинах будет порядок один и тот же? И, если кто знает, было бы интересно.
Exception Type: TypeError at
постепенно осваиваю джанго + питон, взял чужой код с гитхаба, подправил большую часть кода, но при.

TypeError: ‘type’ object is not subscriptable
не могу понять на что компилятор ругается, хочу использовать модуль array выдает ошибку.
How to Handle TypeError: Unhashable Type ‘Dict’ Exception in Python

The Python TypeError: unhashable type: ‘dict’ usually occurs when trying to hash a dictionary, which is an unhashable object. For example, using a dictionary as a key in another dictionary will cause this error. This is because dictionaries only accept hashable data types as a key.
Only immutable objects such as strings, integers and tuples are hashable since they have a single unique value that never changes. Hashing such objects always produces the same result, so they can be used as keys for dictionaries.
TypeError: Unhashable Type: ‘Dict’ Example
Here’s an example of a Python TypeError: unhashable type: ‘dict’ thrown when a dictionary is used as the key for another dictionary:
my_dict = : 'D'> print(my_dict)
Since a dictionary is not hashable, running the above code produces the following error:
File "test.py", line 1, in my_dict = : 'D'> TypeError: unhashable type: 'dict'
How to Fix TypeError: Unhashable Type: ‘Dict’
The Python TypeError: unhashable type: ‘dict’ can be fixed by casting a dictionary to a hashable object such as tuple before using it as a key in another dictionary:
my_dict = ): 'D'> print(my_dict)
In the example above, the tuple() function is used to convert the dictionary to a tuple. The above code runs successfully and produces the correct output:
Track, Analyze and Manage Errors With Rollbar
Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing Python errors easier than ever. Try it today!
Immutable vs. Hashable

I’m fairly certain you’re trying to avoid going down a rabbit-hole complexity, but for me, the definition of “hashable” simply as “a type of object that you can call hash() on” feels incomplete, and almost circular. Sorry. Maybe you should add “beyond that, there be dragons here”?

James Uejio RP Team on April 11, 2020
Hi @Zarata yes good point I tried to simplify it in the video because this course is aimed to not require too much prior knowledge. Here is a good stack overflow answer for anyone who is curious what “Hashable” means: stackoverflow.com/questions/14535730/what-does-hashable-mean-in-python
joefol on June 24, 2020
Hi James, I started to watch your video today in the daytime and was fine to follow your video in the console. Now I’m picking up where I left of and its night time and I’m struggling to work it out (the blue on the black is impossible to work out) with the night light on, maybe a lighter background would help. Thanks
kiran on July 25, 2020
all immutable objects are hashable. but not all hashable objects are immutable.
can you give example for this statement.?

Bartosz Zaczyński RP Team on July 28, 2020
When you talk about Python’s built-in data types, then most of the immutable ones are hashable. These include tuples or frozen sets, for example:
# Immutable and hashable: >>> hash(frozenset(['apple', 'banana', 'orange'])) -501384979540254233
It allows objects of these types to become dictionary keys or set members. On the other hand, instances of built-in mutable types, such as lists, dicts, or sets, are never hashable:
# Mutable but not hashable: >>> hash(set(['apple', 'banana', 'orange'])) Traceback (most recent call last): File "", line 1, in TypeError: unhashable type: 'set'
These can’t be used as dictionary keys, nor can they be added to a set, which both use the hash() function to calculate elements’ location in memory.
However, since the hash is derived from the object’s internal value, sometimes, even the immutable data types won’t be hashable in Python. When you add a mutable element, like a list, to an immutable collection, its collective value will no longer be immutable. Therefore, it won’t be hashable:
# Immutable but not hashable: >>> hash(('apple', 'banana', 'orange', ['a list'])) Traceback (most recent call last): File "", line 1, in TypeError: unhashable type: 'list'
The tuple itself has a fixed set of elements, but one of them is mutable and can be modified without touching the tuple it belongs to.
To answer your question, I’m not aware of any built-in data types that are mutable and hashable at the same time, but user-defined classes have such properties by default:
>>> class MutableAndHashable: . def __init__(self, value): . self.value = value . >>> instance = MutableAndHashable(42) >>> hash(instance) 8789535480438 >>> instance.value = 24 >>> hash(instance) 8789535480438 >>> hash(instance) == id(instance) True
The default hash value of a class instance is the same as its identity. To disable “hashability” of a class, you can specify the __eq__() magic method that compares two instances:
>>> class MutableButNotHashable: . . def __init__(self, value): . self.value = value . . def __eq__(self, other): . if type(self) is type(other): . return self.value == obj.value . return False . >>> instance = MutableButNotHashable(42) >>> hash(instance) Traceback (most recent call last): File "", line 1, in hash(instance) TypeError: unhashable type: 'MutableButNotHashable'
However, when you override the __eq__() method, you almost certainly want to define the __hash__() one as well to adhere to the hash/eq contract. Otherwise, Python won’t use the default hash implementation anymore.
Also, a good hash function needs to have specific properties, such as avoiding so-called “collisions” or distributing elements evenly. But you don’t need to worry about it as long as you delegate to the built-in hash() function.
I hope this clears things up for you.
kiran on July 29, 2020
Вопрос №67033 от пользователя Антон в уроке «Декораторы», курс «Python: Функции»
Добрый день! Не могу победить упражнение. в Репл вроде все работает, но тесты выдают ошибки: TypeError: unsupported operand type(s) for : ‘int’ and ‘NoneType’ AssertionError: Second function should not affect memory of first function E assert None != None Ссылка на код https://ru.hexlet.io/code_reviews/587030 Просьба помочь!
Антон, у вас проблема в том, что вы из ретерна возвращает функцию print. Функция принт выводит значение на экран, но возвращает она None.
Что у вас сейчас получается. В высчитывает результат result. Дальше возвращаете из функции print(result), при это значение result печатается на экран, а из функции возвращается None, т.к. его возвращает None.
Андрей Моисейкин, спасибо тебе милый человек! Вроде поправил, но теперь появилась ошибка: TypeError: unhashable type: ‘dict’
Что я не так в этот раз сделал?
В общем не выдержал и посмотрел решение учителя. Если честно не совсем понял почему мы создаем новый словарь внутри замыкания, если можно менять внешний словарь внутри декоратора и он вроде как перезаписывается и сохраняется. Какая разница? И еще этот непонятный вывод:
E TypeError: unhashable type: ‘dict’
Зачем-то вместо одного значения подставляется словарь.
Антон, в вашем решении две проблемы:
- Вы проверяете на наличие результата в памяти, и если он уже посчитан ранее, вы выводите его на экран, но не возвращаете. У вас возврат в блоке else, в который мы в этом случае не заходим.
- В блоке else вы возвращаете не результата для конкретного аргумента, вы возвращаете весь словарь с уже записанными вычислениями.