首页 文章

Python 3中的不可变字典:如何使keys(),items()和values()字典视图不可变

提问于
浏览
5

Short version: What's the best way to override dict.keys() and friends to keep myself from accidentally modifying my (supposedly) immutable dictionary in Python 3?

在最近的一个问题中,我询问了Hashing an immutable dictionary in Python . 从那时起,我已经 Build 了一个我不满意的不可改变,可以翻译的字典 . 但是,我意识到它有一个漏洞: keys()items()values() 返回的dictionary views仍然允许我不小心改变我的(据称)不可变字典 .

我可以找到有关字典视图的Stack Overflow唯一的问题是Python create own dict view of subset of dictionary,但这似乎与我的问题没什么关系,并且What would a "frozen dict" be?的答案似乎没有超越 keys() 等 .

这样做会阻止我意外修改,例如,我的不可变字典的键吗?

class FrozenCounter(collections.Counter):
    "Model an hashable multiset as an immutable dictionary."
    # ...
    def keys(self):
        return list(super().keys())
    def values(self):
        return list(super().values())
    def items(self):
        return list(super().items())

我从答案中收集到了什么

我主要看不懂 .

dictviews无法修改dicts . 在Python 3 documentation,我误读了,"They provide a dynamic view on the dictionary’s entries, which means that when the dictionary changes, the view reflects these changes"说"when the view changes, the dictionary reflects these changes."显然这不是文件所说的 .

2 回答

  • 4

    在Python 2.x中,视图不允许您改变底层对象:

    >>> a = { 'a' : 1 }
    >>> a.keys()[0] = 'b'
    >>> a
    {'a': 1}
    >>> a.values()[0] = 'b'
    >>> a
    {'a': 1}
    

    在Python 3.x中,变异视图给出了一个TypeError:

    >>> a = { 'a':1}
    >>> a.keys()[0] = 'b'
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: 'dict_keys' object does not support item assignment
    
  • 0

    这可能是一个坏主意,因为它打破了这些方法首先返回视图的假设,并将它们替换为不再更新以匹配底层字典的可变对象 .

    您的观点如何能够改变您的字典?视图不支持项目分配或删除,因此我不相信它们可以更改基础字典 .

相关问题