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

2024-07-08 10:32:20 发布

您现在位置:Python中文网/ 问答频道 /正文

好吧,问题就在标题中:如何定义一个具有不可变键但可变值的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)

但在我看来(毫不奇怪)相当草率。特别是,这是安全的,还是因为我是从dict继承来的,所以有实际更改/添加一些密钥的风险? 谢谢。


Tags: keyinself标题dictionary字典定义init
3条回答

考虑代理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]

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

dict直接继承的问题是很难遵守完整的dict契约(例如,在您的情况下,update方法的行为不一致)。

你想要的是扩展^{}

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

注意,原始的(包装的)dict将被修改,如果不希望发生这种情况,请使用^{} or ^{}

如何阻止某人添加新密钥完全取决于某人尝试添加新密钥的原因。作为comments状态,大多数修改键的dictionary方法不会经过__setitem__,因此.update()调用将添加新键。

如果您只希望有人使用d[new_key] = v,那么您的__setitem__就可以了。如果他们可能使用其他方式添加密钥,那么您必须投入更多的工作。当然,他们也可以用这个来做:

dict.__setitem__(d, new_key, v)

在Python中,您不能使事情真正不变,只能停止特定的更改。

相关问题 更多 >

    热门问题