Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

json

hash

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?

like image 908
Frias Avatar asked Dec 25 '10 22:12

Frias


People also ask

How do you fix a TypeError Unhashable type dict?

The Python "TypeError: unhashable type: 'dict'" occurs when we use a dictionary as a key in another dictionary or as an element in a set . To solve the error, use a frozenset instead, or convert the dictionary into a JSON string before using it as a key.

What does TypeError Unhashable type dict mean?

If you are handling dictionaries containing keys and values, you might have encountered the program error "typeerror unhashable type 'dict'". This means that you are trying to hash an unhashable object. In simple terms, this error occurs when your code tries to hash immutable objects such as a dictionary.

How do you solve the TypeError Unhashable type list?

The “TypeError: unhashable type: 'list'” error is raised when you try to assign a list as a key in a dictionary. To solve this error, ensure you only assign a hashable object, such as a string or a tuple, as a key for a dictionary.

What is Unhashable type in Python?

TypeError: unhashable type: 'list' usually means that you are trying to use a list as an hash argument. This means that when you try to hash an unhashable object it will result an error. For ex. when you use a list as a key in the dictionary , this cannot be done because lists can't be hashed.


1 Answers

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.

like image 199
moinudin Avatar answered Sep 16 '22 23:09

moinudin