为同一字典值创建可交换元组键的最佳方法是什么?

2024-09-30 00:29:28 发布

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

def check():
    dict_choice_a = {(a, b) : value, (b, a) : value}  #(a, b) and (b, a) refer to the same value but repeted
    dict_choice_b = {tuple(sorted((a, b)) : value}  #not repetitive but unreadable
    dict_choice_a[(a, b)] = new_value #need to do twice to change value but more readable than dict_choice_b
    dict_choice_a[(b, a)] = new_value

    #value of both keys are always the same

我想创建一个dictionary,它的元组键引用其值,该键需要作为(a, b) = (b, a)交换,并且它们只引用相同的值。在

这里的问题是:什么是最好的方法,使郁金香元素的钥匙交换,但也指相同的价值。在

此外,字符串也应该在解决方案中起作用。在


Tags: andthetonewvaluedefcheckdict
2条回答

根据注释,可以将a和{}放入一个无序的^{}

dict_choice = {frozenset((a, b)): value}

如果需要自动执行此操作,可以创建自己的^{}

^{pr2}$

使用中:

>>> d = MyDict([((1, 2), 'hello'), ((3, 4), 'world')])
>>> d[(2, 1)]
'hello' 

但是请注意,对于其他类型的键,这可能会有意外的行为:

>>> d['hello'] = 'world'
>>> d['hole']
'world'
>>> d[1] = 2
Traceback (most recent call last):
  File "python", line 1, in <module>
  File "python", line 14, in __setitem__
TypeError: 'int' object is not iterable

使用@jornsharpe解决方案,我为其他类型的键的意外行为创建了一个替代方案,考虑到只有元组将以无序的方式使用:

class MyDict(MutableMapping):

    def __init__(self, arg=None):
        self._map = {}
        if arg is not None:
            self.update(arg)

    def __getitem__(self, key):
        if isinstance(key, tuple):
            return self._map[frozenset(key)]
        return self._map[key]

    def __setitem__(self, key, value):
        if isinstance(key, tuple):
            self._map[frozenset(key)] = value
        else:
            self._map[key] = value

    def __delitem__(self, key):
        if isinstance(key, tuple):
            del self._map[frozenset(key)]
        else:
            del self.map[key]

    def __iter__(self):
        return iter(self._map)

    def __len__(self):
        return len(self._map)

    def __str__(self):
        return str(self._map)

相关问题 更多 >

    热门问题