使用不可变键但可变值定义python字典

use*_*949 10 python dictionary key immutability

好吧,问题在于标题:如何定义具有不可变键但可变值的python字典?我想出了这个(在python 2.x中):

class FixedDict(dict):
    """
    A dictionary with a fixed set of keys
    """

    def __init__(self, dictionary):
        dict.__init__(self)
        for key in dictionary.keys():
            dict.__setitem__(self, key, dictionary[key])

    def __setitem__(self, key, item):
        if key not in self:
            raise KeyError("The key '" +key+"' is not defined")
        dict.__setitem__(self, key, item)
Run Code Online (Sandbox Code Playgroud)

但它看起来(不出所料)相当草率.特别是,这是安全还是存在实际更改/添加某些密钥的风险,因为我是从dict继承的?谢谢.

ber*_*eal 14

直接继承的问题dict在于很难遵守完整dict的合同(例如,在你的情况下,update方法不会以一致的方式运行).

你想要的是扩展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
Run Code Online (Sandbox Code Playgroud)

请注意,原始(包装)字典将被修改,如果您不希望发生这种情况,请使用copydeepcopy.


Kat*_*iel 13

考虑代理dict而不是子类化它.这意味着只允许您定义的方法,而不是回退到dict实现.

class FixedDict(object):
        def __init__(self, dictionary):
            self._dictionary = dictionary
        def __setitem__(self, key, item):
                if key not in self._dictionary:
                    raise KeyError("The key {} is not defined.".format(key))
                self._dictionary[key] = item
        def __getitem__(self, key):
            return self._dictionary[key]
Run Code Online (Sandbox Code Playgroud)

此外,您应该使用字符串格式而不是+生成错误消息,否则它将崩溃任何不是字符串的值.