경우이 도움이 ... 당신은 정말 이런 식으로 뭔가 할 수있는 몇 가지 이유 해쉬 등가물로 unhashable 일을 변환해야하는 경우 :
가
from collections import Hashable, MutableSet, MutableSequence, MutableMapping
def make_hashdict(value):
"""
Inspired by https://stackoverflow.com/questions/1151658/python-hashable-dicts
- with the added bonus that it inherits from the dict type of value
so OrderedDict's maintain their order and other subclasses of dict() maintain their attributes
"""
map_type = type(value)
class HashableDict(map_type):
def __init__(self, *args, **kwargs):
super(HashableDict, self).__init__(*args, **kwargs)
def __hash__(self):
return hash(tuple(sorted(self.items())))
hashDict = HashableDict(value)
return hashDict
def make_hashable(value):
if not isinstance(value, Hashable):
if isinstance(value, MutableSet):
value = frozenset(value)
elif isinstance(value, MutableSequence):
value = tuple(value)
elif isinstance(value, MutableMapping):
value = make_hashdict(value)
return value
my_set = set()
my_set.add(make_hashable(['a', 'list']))
my_set.add(make_hashable({'a': 1, 'dict': 2}))
my_set.add(make_hashable({'a', 'new', 'set'}))
print my_set
내 HashableDict 구현이 간단하고 최소한 엄격한입니다 예 : here. 산세 등을 지원하는 고급 HashableDict가 필요한 경우 다른 많은 구현을 확인하십시오. 위 버전에서 OrderedDicts의 순서를 유지하면서 원본 dict 클래스를 유지하려고했습니다. 나는 또한 속성과 같은 접근을 위해 here에서 AttrDict를 사용한다.
위의 예는 어떤 방식 으로든 권위있는 것이 아니며 세트의 일부 항목을 저장해야하고 비슷한 항목을 먼저 저장해야하는 비슷한 문제에 대한 나의 해결책입니다.
일반적으로 변경할 수없는 것이면 잘못된 키가됩니다. 튜플을 사용해야하는 경우 사용할 수 있습니다. –