Pymongo API TypeError:无法散列的字典 [英] Pymongo API TypeError: Unhashable dict
问题描述
我正在为我的软件编写API,以便更轻松地访问mongodb.
I'm writing an API for my software so that it is easier to access 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字段.
This function is simply meant to find the document who's recid matches the argument and update its creation_date field.
为什么会出现此错误?
推荐答案
很简单,您添加了多余的/多余的花括号,请尝试以下操作:
It's simple, you have added extra/redundant curly braces, try this:
self.collection.find_and_modify(query={"recid":recid},
update={"$set": {"creation_date": str(datetime.now())}})
UPD(解释,假设您使用的是python> = 2.7):
UPD (explanation, assuming you are on python>=2.7):
发生错误是因为python认为您正在尝试使用{}
表示法进行设置:
The error occurs because python thinks you are trying to make a set with {}
notation:
集合类是使用字典实现的.因此, 集合元素的要求与字典的要求相同 钥匙;也就是说,该元素同时定义了__eq __()和__hash __().
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__().
换句话说,集合中的元素应该是可散列的: int
,string
.并且您要向其传递dict
,它不能被散列并且不能作为集合的元素.
In other words, elements of a set should be hashable: e.g. int
, string
. And you are passing a dict
to it, which is not hashable and cannot be an element of a set.
此外,请参见以下示例:
Also, see this example:
>>> {{}}
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'dict'
希望有帮助.
这篇关于Pymongo API TypeError:无法散列的字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!