why dict objects are unhashable in python?

后端 未结 5 1773
悲&欢浪女
悲&欢浪女 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:24

    As others have said, the hash value of a dict changes as the contents change.

    However if you really need to use dicts as keys, you can subclass dict to make a hashable version.

    >>> class hashabledict(dict):
    ...    def __hash__(self):
    ...        return id(self)
    ... 
    >>> hd = hashabledict()
    >>> d = dict()
    >>> d[hd] = "foo"
    >>> d
    {{}: 'foo'}
    
    >>> hd["hello"] = "world"
    >>> d
    {{'hello': 'world'}: 'foo'}
    

    This replaces the hash value used for the dict with the object's address in memory.

提交回复
热议问题