Immutable dictionary, only use as a key for another dictionary

前端 未结 8 2335
情歌与酒
情歌与酒 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:13

    Variation of Raymond Hettinger's answer by wrapping the self._dict with types.MappingProxyType.

    class ImmutableDict(collections.Mapping):
        """
        Copies a dict and proxies it via types.MappingProxyType to make it immutable.
        """
        def __init__(self, somedict):
            dictcopy = dict(somedict) # make a copy
            self._dict = MappingProxyType(dictcopy) # lock it
            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
    
        def __repr__(self):
            return str(self._dict)
    

提交回复
热议问题