vick786
vick786

Reputation: 7

what is the meaning of hashable in dict

why I cannot write this {names: heroes} inside the dictionary .when I did this {{names: heroes} for names, heroes in zip(names, heroes)} an error occurred which is a type error saying unhashable dict. What does that mean?

nums={{names:heroes} for names, heroes in zip(names,heroes)}
print(nums)
Traceback (most recent call last):
  File "C:/Users/ahmod/AppData/Local/Programs/Python/Python37-32/mim.py", line 7, in <module>
    nums={{names:heroes} for names, heroes in zip(names,heroes)}
  File "C:/Users/ahmod/AppData/Local/Programs/Python/Python37-32/mim.py", line 7, in <setcomp>
    nums={{names:heroes} for names, heroes in zip(names,heroes)}
TypeError: unhashable type: 'dict'

Upvotes: 0

Views: 53

Answers (1)

rdas
rdas

Reputation: 21285

{{names: heroes} for names, heroes in zip(names, heroes)}

This is a set comprehension -because you are using the {} curly braces. In a set, each element must be hashable. you are setting each elements in the set to {names: heroes} - which is a dict. So you are trying to make a set of dict.

But unfortunately, in python, dict is not hashable - since it's a mutable type.

So you can't do that.

Instead you can try to create a dictionary directly:

{name: heroe for name, heroe in zip(names, heroes)}

By just removing the extra curly braces.

Upvotes: 1

Related Questions