Pymongo API TypeError: Unhashable dict [英] Pymongo API TypeError: Unhashable dict

查看:35
本文介绍了Pymongo API 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 type: 'dict'.

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

为什么会出现这个错误?

解决方案

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

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

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

发生错误是因为 python 认为您正在尝试使用 {} 表示法创建集合:

<块引用>

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

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

另外,请看这个例子:

<预><代码>>>>{{}}回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 <module> 中类型错误:不可散列的类型:'dict'

希望有所帮助.

I'm writing an API for my software so that it is easier to access mongodb.

I have this line:

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

Which throws TypeError: Unhashable type: 'dict'.

This function is simply meant to find the document who's recid matches the argument and update its creation_date field.

Why is this error occuring?

解决方案

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 (explanation, assuming you are on python>=2.7):

The error occurs because python thinks you are trying to make a set with {} notation:

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__().

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'

Hope that helps.

这篇关于Pymongo API TypeError: Unhashable dict的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆