16

我正在为我的软件编写一个 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'

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

为什么会出现这个错误?

4

1 回答 1

21

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

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

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

发生错误是因为 python 认为您正在尝试使用{}符号进行设置:

集合类是使用字典实现的。因此,对集合元素的要求与对字典键的要求相同;也就是说,该元素同时定义了 __eq__() 和 __hash__()。

换句话说,集合的元素应该是可散列的:例如intstring. 而且您将 a 传递dict给它,它不是可散列的,也不能是集合的元素。

另外,请参阅此示例:

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

希望有帮助。

于 2013-07-16T10:32:25.950 回答