python - "frozen dict"是什么?

标签 python dictionary data-structures immutability

  • 卡住集是卡住集。
  • 卡住列表可以是一个元组。
  • 卡住的字典是什么?一个不可变的、可散列的字典。

我猜它可能类似于 collections.namedtuple,但这更像是一个 freeze-keys dict(半卡住 dict)。不是吗?

一个“frozendict”应该是一个卡住字典,它应该有keysvaluesget等,并且支持infor

更新:
* 它是:https://www.python.org/dev/peps/pep-0603

最佳答案

Python 没有内置的 frozendict 类型。事实证明这不会经常有用(尽管它可能仍然比 frozenset 更有用)。

需要这种类型的最常见原因是在内存具有未知参数的函数的函数调用时。存储 dict 的可散列等效项(其中值是可散列的)的最常见解决方案类似于 tuple(sorted(kwargs.items()))

这取决于排序是否有点疯狂。 Python 不能肯定地 promise 排序会在这里产生一些合理的结果。 (但它不能 promise 太多其他东西,所以不要太担心。)


您可以轻松地制作某种类似于 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'

关于python - "frozen dict"是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2703599/

相关文章:

python:使用队列将字典传递给另一个线程

Python:将表转换为字符串为键:值对并存储在字典中

c - 为结构中的变量分配内存的最佳方法是什么?

perl - 如何在 Perl 中创建散列的散列?

java - Java 中的复杂数据结构

Python如何替换数据框中的列值

python - 如何在EMR核心节点上启用python库以启动EMR Spark应用程序步骤

python - 有没有办法使用 argparse 模块输入以 '-' 符号开头的字符串作为命令行参数? (不使用标志)

python - 提取数据帧中第一个值和最后一个值之间的最大连续缺失值

python - 获取所有子词典的key