TypeError:不可损坏的类型:“dict”Python/Flask

2024-04-26 17:00:33 发布

您现在位置:Python中文网/ 问答频道 /正文

所以,我正在开发一个小程序,它应该向firestore database发送值,几乎所有的东西都工作正常,但是我从这部分代码中得到了一个错误。我正在试图保存string中的temp

 if block == "ITEMS":
        champs = form.areaItems.data #Get the user input text field from the WTForm (it's a dict for whatever reason)
        itemsChamps = ItemsChamps(champs.values()) #Stock the dict value inside itemsChamps 
        temp = next(iter(itemsChamps.name)) #Get the 1st value from itemsChamps (I only want the 1st value)
        data = {
            "items": {
                champs: {
                    "string": temp
                }
            }
        }

以下是错误:

File "C:\[..]\flaskblog\routes.py", line 63, in ajouter

"string": temp

TypeError: unhashable type: 'dict'

我的代码可能看起来有点“混乱”,我是个新手,很抱歉

编辑1:现在可以了

我现在觉得自己很笨,我被我写的所有代码弄糊涂了,有一些错误:

        if block == "ITEMS":
        champs = form.itemsFields.data #I was using the wrong form field...
        itemsChamps = ItemsChamps(form.areaItems.data.values()) #I'm now getting all the value from the right field
        temp = next(iter(itemsChamps.name)) #Didn't touch this, it work
        data = {
            "items": {
                champs: {
                    "string": temp
                }
            }
        }

谢谢你给我一点时间


Tags: the代码fromformfielddatastringif
2条回答

问题在于这段代码champs是一个字典,您将它用作键,dict键必须是str、int、float(通常是可以散列而不是字典的东西)

data = {
            "items": {
                champs: {
                    "string": temp
                }
            }
        }

如果champs["user_input"]是您感兴趣的数据,您可以将champs更改为champs["user_input"]以解决此问题

您试图使用dict作为dict键,引用您的评论:“是出于某种原因的dict”。dict是不可散列的,因此不能用作键。也许从dict中提取数据并将其用作密钥

相关问题 更多 >