why dict objects are unhashable in python?

后端 未结 5 1767
悲&欢浪女
悲&欢浪女 2020-12-03 20:37

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

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

5条回答
  •  情歌与酒
    2020-12-03 21:20

    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.

提交回复
热议问题