TypeError: unhashable type: 'dict' when a dict is used as a key for another dict

I have this piece of code:

for element in json[referenceElement].keys(): 

When I run this code, I get this error:

TypeError: unhashable type: 'dict'

What is the cause of this error and what can I do to fix it?

+43
json python hash
Dec 25 '10 at 22:33
source share
2 answers

From this error, I conclude that referenceElement is a dictionary (see below). A dictionary cannot be hashed and therefore cannot be used as a key to another dictionary (or to itself!).

 >>> d1, d2 = {}, {} >>> d1[d2] = 1 Traceback (most recent call last): File "<input>", line 1, in <module> TypeError: unhashable type: 'dict' 

You probably meant either for element in referenceElement.keys() or for element in json['referenceElement'].keys() . With a lot of context, what types of json and referenceElement and what they contain, we can better help you if none of the solutions work.

+54
Dec 25 '10 at 22:37
source share

It seems to me that by calling the key method, you return a python object to python when searching for a list or tuple. Therefore, try to take all the keys in the dictionary, putting them in a list, and then using the for loop.

+1
Dec 25 '10 at 22:39
source share



All Articles