Define a python dictionary with immutable keys but mutable values

前端 未结 3 1715
陌清茗
陌清茗 2021-01-04 10:04

Well, the question is in the title: how do I define a python dictionary with immutable keys but mutable values? I came up with this (in python 2.x):

class Fi         


        
3条回答
  •  甜味超标
    2021-01-04 10:31

    The problem with direct inheritance from dict is that it's quite hard to comply with the full dict's contract (e.g. in your case, update method won't behave in a consistent way).

    What you want, is to extend the collections.MutableMapping:

    import collections
    
    class FixedDict(collections.MutableMapping):
        def __init__(self, data):
            self.__data = data
    
        def __len__(self):
            return len(self.__data)
    
        def __iter__(self):
            return iter(self.__data)
    
        def __setitem__(self, k, v):
            if k not in self.__data:
                raise KeyError(k)
    
            self.__data[k] = v
    
        def __delitem__(self, k):
            raise NotImplementedError
    
        def __getitem__(self, k):
            return self.__data[k]
    
        def __contains__(self, k):
            return k in self.__data
    

    Note that the original (wrapped) dict will be modified, if you don't want that to happen, use copy or deepcopy.

提交回复
热议问题