gpt4 book ai didi

python - Pymongo API 类型错误 : Unhashable dict

转载 作者:太空狗 更新时间:2023-10-29 20:47:50 26 4
gpt4 key购买 nike

我正在为我的软件编写 API,以便更轻松地访问 mongodb。

我有这一行:

def update(self, recid):        
self.collection.find_and_modify(query={"recid":recid}, update={{ "$set": {"creation_date":str( datetime.now() ) }}} )

抛出 TypeError: Unhashable type: 'dict'

这个函数只是为了找到 recid 与参数匹配的文档并更新其 creation_date 字段。

为什么会出现这个错误?

最佳答案

很简单,你添加了额外/多余的花括号,试试这个:

self.collection.find_and_modify(query={"recid":recid}, 
update={"$set": {"creation_date": str(datetime.now())}})

UPD(解释,假设您使用的是 python>=2.7):

发生错误是因为 python 认为您正在尝试使用 {} 符号来创建集合:

The set classes are implemented using dictionaries. Accordingly, the requirements for set elements are the same as those for dictionary keys; namely, that the element defines both __eq__() and __hash__().

换句话说,集合的元素应该是可散列的:例如整数字符串。您正在向它传递一个 dict,它不可散列,也不能是集合的元素。

另请参阅此示例:

>>> {{}}
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'dict'

希望对您有所帮助。

关于python - Pymongo API 类型错误 : Unhashable dict,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17674100/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com