我想它可能类似于collections.namedtuple,但这更像是一个冻结键的字典(一个半冻结的字典)。不是吗?
collections.namedtuple
“frozendict”应该是一个冻结字典,它应该有keys, values,get等,并且支持in,for等。
keys
values
get
in
for
更新: *它是:https ://www.python.org/dev/peps/pep-0603
Python 没有内置的 frozendict 类型。事实证明这不会经常有用(尽管它可能仍然比frozenset现在更有用)。
frozenset
需要这种类型的最常见原因是在记忆函数调用具有未知参数的函数时。存储 dict 的可散列等效项(其中值是可散列的)的最常见解决方案类似于tuple(sorted(kwargs.items())).
tuple(sorted(kwargs.items()))
这取决于排序是否有点疯狂。Python 不能肯定地承诺排序会在这里产生一些合理的结果。(但它不能承诺太多其他东西,所以不要太多汗水。)
你可以很容易地制作某种类似于 dict 的包装器。它可能看起来像
import collections class 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 y False >>> x == y True >>> x == {'a': 1, 'b': 2} True >>> d = {x: 'foo'} >>> d[y] 'foo'