Python没有内置的Frozendict类型。事实证明,这并不是太有用了(尽管它可能仍然比以前有用
frozenset)。
想要这种类型的最常见原因是在记忆函数调用具有未知参数的函数时。存储dict(其中值是可哈希的)的可哈希等效的最常见解决方案是
tuple(sorted(kwargs.iteritems()))。
这取决于排序是否有点疯狂。Python无法肯定地承诺排序将在这里产生合理的结果。(但是它不能保证其他任何事情,所以不要过多地出汗。)
您可以轻松地制作某种类似于dict的包装器。它可能看起来像
import collectionsclass FrozenDict(collections.Mapping): """Don't forget the docstrings!!""" def __init__(self, *args, **kwargs): self._d = dict(*args, **kwargs) self._hash = None def __iter__(self): return iter(self._d) def __len__(self): return len(self._d) def __getitem__(self, key): return self._d[key] def __hash__(self): # It would have been simpler and maybe more obvious to # use hash(tuple(sorted(self._d.iteritems()))) from this discussion # so far, but this solution is O(n). I don't know what kind of # n we are going to run into, but sometimes it's hard to resist the # urge to optimize when it will gain improved algorithmic performance. if self._hash is None: hash_ = 0 for pair in self.items(): hash_ ^= hash(pair) self._hash = hash_ return self._hash
它应该很棒:
>>> x = FrozenDict(a=1, b=2)>>> y = FrozenDict(a=1, b=2)>>> x is yFalse>>> x == yTrue>>> x == {'a': 1, 'b': 2}True>>> d = {x: 'foo'}>>> d[y]'foo'


