why dict objects are unhashable in python?

I mean why cant we put key of dict as dict?

that means we can't have dictionary having key as another dictionary...


Solution 1:

Short answer: because they are mutable containers.

If a dict was hashed, its hash would change as you changed its contents.

Solution 2:

This is easy to deal with. Wrap a dict in a frozenset before you hash it. Then, when you need to use it, convert it back to a dict.

>>> unhashable = {'b': 'a', 'a': 'b'}
>>> hashable = frozenset(unhashable.items())
>>> unhashable = dict(hashable)
>>> unhashable
{'a': 'b', 'b': 'a'}

Note that dictionary key order is undefined anyway, so the change in key order doesn't matter.