Python 缺少frozen-dict 类型的解决方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39440190/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 22:16:37  来源:igfitidea点击:

A workaround for Python's missing frozen-dict type?

pythondictionaryimmutability

提问by SomethingSomething

In Python, when you want to use lists as keys of some dictionary, you can turn them into tuples, which are immutable and hence are hashable.

在 Python 中,当你想使用列表作为某个字典的键时,你可以将它们转换成元组,元组是不可变的,因此是可散列的。

>>> a = {}
>>> a[tuple(list_1)] = some_value
>>> a[tuple(list_2)] = some_other_value

The same happens when you want to use setobjects as keys of some dictionary - you can build a frozenset, that is again immutable and hence is hashable.

当您想使用set对象作为某个字典的键时,也会发生同样的情况- 您可以构建一个freezeset,它也是不可变的,因此是可散列的。

>>> a = {}
>>> a[frozenset(set_1)] = some_value
>>> a[frozenset(set_2)] = some_other_value

But it seems that for dictionary there is no equivalent.

但似乎字典没有等价物。

A first idea I thought about (and found it bad finally), is to use str(some_dict)as a key. But, dictionaries always use different hash functions, so strings of equal dictionaries may be different.

我想到的第一个想法(最后发现它很糟糕)是str(some_dict)用作钥匙。但是,字典总是使用不同的哈希函数,因此相同字典的字符串可能不同。

Is there any workaround known as a good practice, or does anyone have other ideas how to use dictionary-like objects as keys of other dictionaries?

是否有任何称为良好实践的解决方法,或者是否有人有其他想法如何使用类似字典的对象作为其他字典的键?

回答by SomethingSomething

I've found a nice workaround for this problem, which is building a frozensetcontaining the dictionary items:

我为这个问题找到了一个很好的解决方法,它正在构建一个包含字典项目的frozenset

>>> a = {'key1' : 'val1', 'key2' : 'val2'}
>>> b = frozenset(a.items())
>>> frozenset_restored_to_dict = dict(b)
>>> frozenset_restored_to_dict
{'key2': 'val2', 'key1': 'val1'}

As can be seen in the code, bis a frozenset, which is immutable and hashable, and can be totally restored to be a regular dictionary like a.

从代码中可以看出,b是一个frozenset,它是不可变和可散列的,并且可以完全恢复为像a.

回答by Andrey Rusanov

You can try ordered dictor look on these answers:

您可以尝试ordered dict或查看以下答案:

and there is even a package on PyPI: https://pypi.python.org/pypi/frozendict

PyPI 上甚至还有一个包:https://pypi.python.org/pypi/frozendict

You can also simply convert dict to tuples(sorted(your_dict.items())) and then use as a hash.

您也可以简单地将 dict 转换为 tuples( sorted(your_dict.items())),然后用作散列。

UPD: as mentioned in comments, OrderedDict is unhashable. My bad, it is really should not be hashable since it is mutable.

UPD:正如评论中提到的,OrderedDict 是不可哈希的。我的错,它真的不应该是可散列的,因为它是可变的。