问题描述
(b,a):value}(a,b)和(b,...) a)引用相同的值但重复dict_choice_b = {tuple(sorted((a,b)):value} #not重复但不可读
dict_choice_a [(a,b)] = new_value #need做两次来改变价值,但比dict_choice_b更可读的
dict_choice_a [(b,a)] = new_value
两个键的#value总是相同的
我想创建一个字典
,它具有引用其值的元组键,密钥需要作为(a,b)=(b,a)
可交换,并且它们仅引用相同的值。
$ b $这是一个问题:什么是最好的方式来使密钥的元素可以互换,但也可以引用相同的值。
此外,字符串应该
根据评论,您可以将 a
和 b
进入,这是无序的:
dict_choice = {frozenset((a,b)):价值}
如果你需要这个是自动的,您可以创建自己的:
class MyDict(MutableMapping):
pre>
def __init __(self,arg = None):
self._map = {}
如果arg不是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'
不过请注意,与其他种类的密钥有意想不到的行为:
>>> d ['hello'] ='world'
>>> d ['hole']
'world'
>>> d [1] = 2
追溯(最近的最后一次呼叫):
文件python,第1行,< module>
文件python,第14行,__setitem__
TypeError:'int'对象不可迭代
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
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.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.
解决方案Per the comments, you can put
a
andb
into afrozenset
, which is unordered:dict_choice = {frozenset((a, b)): value}
If you need this to be automatic, you could create your own
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)
In use:
>>> 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
这篇关于为相同的字典值创建可交换的元组键的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!