【问题标题】:How to create a python dictionary only accepts uniques mutable objects如何创建 python 字典只接受唯一的可变对象
【发布时间】:2019-09-17 22:09:17
【问题描述】:

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

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

【问题讨论】:

  • 隐含地,你必须做类似的事情。因为只有键可以是唯一的,而不是值,所以你所做的就是它应该做的方式。
  • 你知道是否已经有模式(或成语)可以解决我的问题吗?

标签: python dictionary data-structures set mutable


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2013-04-12
    • 2012-06-16
    • 1970-01-01
    • 2019-12-05
    • 1970-01-01
    • 1970-01-01
    • 2019-02-08
    • 2020-03-03
    • 2014-06-21
    相关资源
    最近更新 更多