Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pymongo API TypeError: Unhashable 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?

like image 966
JakeCowton Avatar asked Jul 16 '13 10:07

JakeCowton


1 Answers

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.

like image 79
alecxe Avatar answered Sep 20 '22 13:09

alecxe