What's The Best Way To Create Exchangeable Tuple Keys For The Same Dictionary Value?
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 r
Solution 1:
Per the comments, you can put a
and b
into a frozenset
, which is unordered:
dict_choice = {frozenset((a, b)): value}
If you need this to be automatic, you could create your own MutableMapping
:
classMyDict(MutableMapping):
def__init__(self, arg=None):
self._map = {}
if arg isnotNone:
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):
returniter(self._map)
def__len__(self):
returnlen(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'objectisnot iterable
Solution 2:
Using @jonrsharpe solution, I created an alternative for the unexpected behavior with other kinds of keys, considered that only tuples will be used in an unordered way:
classMyDict(MutableMapping):
def__init__(self, arg=None):
self._map = {}
if arg isnotNone:
self.update(arg)
def__getitem__(self, key):
ifisinstance(key, tuple):
return self._map[frozenset(key)]
return self._map[key]
def__setitem__(self, key, value):
ifisinstance(key, tuple):
self._map[frozenset(key)] = value
else:
self._map[key] = value
def__delitem__(self, key):
ifisinstance(key, tuple):
del self._map[frozenset(key)]
else:
del self.map[key]
def__iter__(self):
returniter(self._map)
def__len__(self):
returnlen(self._map)
def__str__(self):
returnstr(self._map)
Post a Comment for "What's The Best Way To Create Exchangeable Tuple Keys For The Same Dictionary Value?"