Pymongo API TypeError: Unhashable dict

醉酒当歌 提交于 2020-01-02 02:01:06

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/17674100/pymongo-api-typeerror-unhashable-dict

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!