什么是“冻结的字典"?是? [英] What would a "frozen dict" be?

查看:23
本文介绍了什么是“冻结的字典"?是?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  • 冻结集是冻结集.
  • 冻结列表可以是元组.
  • 冻结的字典会是什么?一个不可变的、可散列的字典.

我想它可能类似于 collections.namedtuple,但这更像是一个冻结键的字典(半冻结​​的字典).不是吗?

一个frozendict"应该是一个冻结的字典,它应该有keysvaluesget等,并且支持infor

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

解决方案

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

需要这种类型的最常见原因是在记忆具有未知参数的函数的函数调用时.存储 dict 的可哈希等价物(其中值是可哈希的)的最常见解决方案是类似于 tuple(sorted(kwargs.iteritems())).

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

<小时>

你可以很容易地制作某种类似于 dict 的包装器.它可能看起来像

导入集合类 FrozenDict(collections.Mapping):"""不要忘记文档字符串!!"""def __init__(self, *args, **kwargs):self._d = dict(*args, **kwargs)self._hash = 无def __iter__(self):返回迭代器(self._d)def __len__(self):返回 len(self._d)def __getitem__(self, key):返回 self._d[key]def __hash__(self):# 这本来会更简单,也许更明显# 使用本次讨论中的 hash(tuple(sorted(self._d.iteritems())))# 到目前为止,但这个解决方案是 O(n).我不知道是什么样的# n 我们会遇到,但有时很难抗拒# 敦促优化何时会获得改进的算法性能.如果 self._hash 是 None:哈希_ = 0对于 self.items() 中的配对:hash_ ^= 哈希(对)self._hash = hash_返回 self._hash

它应该很好用:

<预><代码>>>>x = FrozenDict(a=1, b=2)>>>y = FrozenDict(a=1, b=2)>>>x 是 y错误的>>>x == y真的>>>x == {'a': 1, 'b': 2}真的>>>d = {x: 'foo'}>>>d[y]'富'

  • A frozen set is a frozenset.
  • A frozen list could be a tuple.
  • What would a frozen dict be? An immutable, hashable dict.

I guess it could be something like collections.namedtuple, but that is more like a frozen-keys dict (a half-frozen dict). Isn't it?

A "frozendict" should be a frozen dictionary, it should have keys, values, get, etc., and support in, for, etc.

update :
* there it is : https://www.python.org/dev/peps/pep-0603

解决方案

Python doesn't have a builtin frozendict type. It turns out this wouldn't be useful too often (though it would still probably be useful more often than frozenset is).

The most common reason to want such a type is when memoizing function calls for functions with unknown arguments. The most common solution to store a hashable equivalent of a dict (where the values are hashable) is something like tuple(sorted(kwargs.iteritems())).

This depends on the sorting not being a bit insane. Python cannot positively promise sorting will result in something reasonable here. (But it can't promise much else, so don't sweat it too much.)


You could easily enough make some sort of wrapper that works much like a dict. It might look something like

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

It should work great:

>>> 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'

这篇关于什么是“冻结的字典"?是?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆