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

问题描述 投票:0回答:1

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

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

我编码了一个从Dictionary类继承的类Container,以存储值(带有唯一键),然后添加了一个set,以跟踪字典中的值,即:

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,以检查值是否尚未存储,但我不确定是否已经存在数据结构来解决我的问题。

python dictionary data-structures set mutable
1个回答
0
投票

制作另一个有价元素字典,并在将值添加到原始字典中(如果存在)之前进行检查,然后不添加。

© www.soinside.com 2019 - 2024. All rights reserved.