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

2023-08-31Python开发问题
2

本文介绍了为相同的字典值创建可交换元组键的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

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)并且它们只引用相同的值.

I want to create a dictionary that has tuple keys referred to its values, that keys need to be exchangeable as (a, b) = (b, a) and they only refer to the same value.

这里的问题是:使 tulpe of keys 的元素可交换但也引用相同值的最佳方法是什么.

Here's the question is: what is the best way to make the element of tulpe of keys exchangeable but also refer to the same value.

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

Moreover, string should be also work in the solution.

推荐答案

根据评论,您可以将 ab 放入一个 frozenset,这是无序的:

Per the comments, you can put a and b into a frozenset, which is unordered:

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

<小时>

如果您需要它是自动的,您可以创建自己的 MutableMapping:

class MyDict(MutableMapping):

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

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

    def __setitem__(self, key, value):
        self._map[frozenset(key)] = value

    def __delitem__(self, key):
        del self._map[frozenset(key)]

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

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

使用中:

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

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

However note that this could have unexpected behaviour with other kinds of keys:

>>> 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

这篇关于为相同的字典值创建可交换元组键的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

在xarray中按单个维度的多个坐标分组
groupby multiple coords along a single dimension in xarray(在xarray中按单个维度的多个坐标分组)...
2024-08-22 Python开发问题
15

Pandas中的GROUP BY AND SUM不丢失列
Group by and Sum in Pandas without losing columns(Pandas中的GROUP BY AND SUM不丢失列)...
2024-08-22 Python开发问题
17

GROUP BY+新列+基于条件的前一行抓取值
Group by + New Column + Grab value former row based on conditionals(GROUP BY+新列+基于条件的前一行抓取值)...
2024-08-22 Python开发问题
18

PANDA中的Groupby算法和插值算法
Groupby and interpolate in Pandas(PANDA中的Groupby算法和插值算法)...
2024-08-22 Python开发问题
11

PANAS-基于列对行进行分组,并将NaN替换为非空值
Pandas - Group Rows based on a column and replace NaN with non-null values(PANAS-基于列对行进行分组,并将NaN替换为非空值)...
2024-08-22 Python开发问题
10

按10分钟间隔对 pandas 数据帧进行分组
Grouping pandas DataFrame by 10 minute intervals(按10分钟间隔对 pandas 数据帧进行分组)...
2024-08-22 Python开发问题
11