加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – Pymongo API TypeError:不可用的字典

发布时间:2020-12-16 23:03:45 所属栏目:Python 来源:网络整理
导读:我正在为我的软件编写API,以便更容易访问 mongodb. 我有这条线: def update(self,recid): self.collection.find_and_modify(query={"recid":recid},update={{ "$set": {"creation_date":str( datetime.now() ) }}} ) 抛出TypeError:Unhashable类型:’dict
我正在为我的软件编写API,以便更容易访问 mongodb.

我有这条线:

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

抛出TypeError:Unhashable类型:’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__().

换句话说,集合的元素应该是可以清除的:例如,int,string.而你正在传递一个字典,它不是可以清洗的,也不能成为一个集合的元素.

另外,请看这个例子:

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

希望有所帮助.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读