Immutable dictionary, only use as a key for another dictionary

前端 未结 8 2328
情歌与酒
情歌与酒 2020-12-05 04:52

I had the need to implement a hashable dict so I could use a dictionary as a key for another dictionary.

A few months ago I used this implementation: Python hashable

8条回答
  •  [愿得一人]
    2020-12-05 05:29

    The Mapping abstract base class makes this easy to implement:

    import collections
    
    class ImmutableDict(collections.Mapping):
        def __init__(self, somedict):
            self._dict = dict(somedict)   # make a copy
            self._hash = None
    
        def __getitem__(self, key):
            return self._dict[key]
    
        def __len__(self):
            return len(self._dict)
    
        def __iter__(self):
            return iter(self._dict)
    
        def __hash__(self):
            if self._hash is None:
                self._hash = hash(frozenset(self._dict.items()))
            return self._hash
    
        def __eq__(self, other):
            return self._dict == other._dict
    

提交回复
热议问题