缺少Python的冻结字典类型的解决方法? [英] A workaround for Python's missing frozen-dict type?
问题描述
在Python中,当您想将列表用作某些字典的键时,可以将它们变成元组,它们是不可变的,因此是可哈希的.
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.
>>> a = {}
>>> a[tuple(list_1)] = some_value
>>> a[tuple(list_2)] = some_other_value
当您要使用 set 对象作为某些字典的键时,也会发生同样的情况-您可以构建一个 frozenset ,它又是不可变的,因此是可哈希的.>
The same happens when you want to use set objects as keys of some dictionary - you can build a frozenset, that is again immutable and hence is hashable.
>>> a = {}
>>> a[frozenset(set_1)] = some_value
>>> a[frozenset(set_2)] = some_other_value
但是似乎字典没有对应的内容.
But it seems that for dictionary there is no equivalent.
我想到的第一个想法(最终发现它很糟糕)是使用str(some_dict)
作为键.但是,字典始终使用不同的哈希函数,因此,相等字典的字符串可能会有所不同.
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.
有没有一种好的方法,或者有人有其他想法如何将类似字典的对象用作其他字典的键?
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?
推荐答案
我找到了解决此问题的好方法,它正在构建包含字典项的 frozenset :
I've found a nice workaround for this problem, which is building a frozenset containing the dictionary items:
>>> a = {'key1' : 'val1', 'key2' : 'val2'}
>>> b = frozenset(a.items())
>>> frozenset_restored_to_dict = dict(b)
>>> frozenset_restored_to_dict
{'key2': 'val2', 'key1': 'val1'}
从代码中可以看出,b
是一个冻结集,它是不可变的且可哈希的,并且可以完全还原为像a
这样的常规词典.
As can be seen in the code, b
is a frozenset, which is immutable and hashable, and can be totally restored to be a regular dictionary like a
.
这篇关于缺少Python的冻结字典类型的解决方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!