2013-07-16 12 views
6

Sto scrivendo un'API per il mio software in modo che sia più semplice accedere a mongodb.Tipo API PymongoErrore: Inibito dict

ho questa linea:

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

che getta TypeError: Unhashable type: 'dict'.

Questa funzione è semplicemente pensata per trovare il documento che recid corrisponde all'argomento e aggiorna il suo campo creation_date.

Perché si verifica questo errore?

risposta

10

E 'semplice, sono stati aggiunti/ridondanti parentesi in più graffe, provate questo:

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

UPD (spiegazione, supponendo che si sono su Python> = 2.7):

L'errore si verifica a causa di pitone pensa si sta tentando di fare un set con {} notazione:

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 altre parole, elementi di un insieme devono essere hashable: ad esempio, int, string. E stai passando un dict ad esso, che non è lavabile e non può essere un elemento di un set.

Inoltre, si veda questo esempio:

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

Speranza che aiuta.

+0

Wow, geniale! Ma perché questo ha causato un tale problema? – RockJake28

+1

Ho migliorato la risposta, per favore controlla. – alecxe

+0

Grazie, ho chiarito molte altre cose anche per me! – RockJake28