如何创建 python 字典只接受唯一可变对象

How to create a python dictionary only accepts uniques mutable objects

提问人:rvcristiand 提问时间:9/18/2019 最后编辑:rvcristiand 更新时间:2/25/2020 访问量:98

问:

我的问题可以分为两部分。第一个是字典中不允许超过两个相等的值。例如,我有这个类:

class MyClass():
    def __init__(self, a, b, c):
        self.a = a
        self.b = b
        self.c = c

    def __key(self):
        return tuple(self.__dict__[key] for key in self.__dict__)

    def __eq__(self, other):
        if isinstance(other, type(self)):
            return self.__key() == other.__key()

        return NotImplemented

我想在这样的字典中创建和存储许多对象

if __name__ == '__main__':
    obj1 = MyClass(1, 2, 3)
    obj2 = MyClass(3, 4, 5)
    obj3 = MyClass(1, 2, 3)

    myDict = {}  # empty dictionary

    myDict['a'] = obj1  # one key-value item
    myDict['b'] = obj2  # two key-value items
    myDict['c'] = obj3  # not allowed, value already stored

如何确定obj3不能存储在字典中?

我问题的第二部分是跟踪可变对象何时更改以避免它等于字典中的其他值,即:

    obj2.a = 1; obj2.b = 2; obj2.c = 3  # not allowed

我编写了一个从字典类继承的类 Container 来存储值(使用唯一键),并添加了一个集合来跟踪字典中的值,即:

class MyContainer(dict):
    def __init__(self):
        self.unique_objects_values = set()

    def __setitem__(self, key, value):
        if key not in self:  # overwrite not allowed
            if value not in self.unique_object_values:  # duplicate objects values don't allowed
                super(MyContainer, self).__setitem__(key, value)
                self.unique_object_values.add(value)
            else:
                print("Object already exist. Object didn't stored")
        else:
            print("Key already exist. Object didn't stored")

并添加父成员以检查值是否尚未存储,但我不太确定是否已经存在数据结构来解决我的问题。MyClass

字典 数据结构 设置 可变

评论

1赞 harmands 9/19/2019
隐含地,你必须做类似的事情。因为只有键可以是唯一的,而不是值,所以你所做的是它应该做的事情。
0赞 rvcristiand 9/19/2019
你知道是否已经有一个模式(或成语)来解决我的问题吗?

答:

0赞 Shivam Kalra 2/25/2020 #1

制作另一个值元素的字典,并在将值添加到原始字典之前进行检查,如果它存在,则不要添加。