Pymongo API TypeError:无法散列的字典
我正在为我的软件编写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认为您正在尝试使用
{}
符号进行设置:集合类使用字典来实现。因此,对设置元素的要求与对字典键的要求相同。也就是说,该元素同时定义了__eq ()和__hash ()。
换句话说,集合中的元素应该是可哈希的:例如
int
,string
。并且您正在传递dict
给它,该值不可散列并且不能是集合的元素。另外,请参见以下示例:
>>> {{}} Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unhashable type: 'dict'
希望能有所帮助。