如果有帮助的话... 如果您确实需要将不可哈希的东西转换为可哈希的等价物,那么您可能会做出以下操作:
from collections import Hashable, MutableSet, MutableSequence, MutableMapping
def make_hashdict(value):
"""
Inspired by https://dev59.com/nnM_5IYBdhLWcg3w9oQA
- 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实现是来自于这里最简单、最不严谨的例子。如果您需要一个更高级的HashableDict,支持pickling和其他功能,请查看许多其他的实现。在我上面的版本中,我想保留原始的dict类,从而保留OrderedDicts的顺序。我还使用了来自这里的AttrDict进行类似属性的访问。
上述示例不具有任何权威性,只是我解决类似问题时的解决方案,其中我需要在集合中存储一些东西,并需要先将它们“哈希化”。