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

169,385

Solution 1

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

>>> 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 more context on what types json and referenceElement are and what they contain, we will be able to better help you if neither solution works.

Solution 2

What it seems like to me is that by calling the keys method you're returning to python a dictionary object when it's looking for a list or a tuple. So try taking all of the keys in the dictionary, putting them into a list and then using the for loop.

Share:
169,385
Frias
Author by

Frias

Updated on January 06, 2020

Comments

  • Frias
    Frias over 4 years

    I have this piece of code:

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

    When I run that code, I get this error:

    TypeError: unhashable type: 'dict'

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

  • Shayne
    Shayne over 5 years
    No. Thats not it at all. .keys() returns a list. The problem is the ReferenceElement he's sending is forbidden (You can't use a dict as a key, likely a restriction to stop you passing itself as its own key, which would be.... absurd)