使用 frozen set 作为 Dict 键是否安全?

Is it safe to use frozen set as Dict key?

显然可以,但是是否存在两组相同元素恰好在Dict中添加两个条目的情况?我想我早些时候遇到了这种情况,并将我的代码从 frozenset(...) 更改为 tuple(sorted(frozenset(...)))。知道 Dict 和 frozenset 实现方式的人可以确认是否需要这样做吗?

frozenset 用作 dict 密钥是否安全? 是。

根据文档,Frozenset 是可散列的,因为它是不可变的。这意味着它可以用作字典的键,因为键的先决条件是它是可哈希的。

来自FrozenSet docs

The frozenset type is immutable and hashable — its contents cannot be altered after it is created; it can therefore be used as a dictionary key or as an element of another set.

并且冗余地,来自Dictionary docs

...keys, which can be any immutable type


澄清一下,一组(根据定义),无论是否冻结,都不会保留顺序。它们在内部存储时不考虑顺序并删除了重复元素,因此以不同顺序构建的两个集合将是字典中的等效键——它们是相同的。

>>> frozenset([1,2,2,3,3]) == frozenset([3,2,1,1,1])
True

同样,

>>> d = {}
>>> d[frozenset([1,1,2,3])] = 'hello'
>>> d[frozenset([1,2,3,3])]
'hello'
>>> d[frozenset([3,3,3,2,1,1,1])]
'hello'
>>> d[frozenset([2,1,3])]
'hello'

来自 the official docs

The frozenset type is immutable and hashable — its contents cannot be altered after it is created; it can therefore be used as a dictionary key or as an element of another set.

(重点是我的)

are there cases where two sets of same elements happen to add two entries in Dict?

没有。 frozenset hashing algorithm 不依赖于元素的顺序,只依赖于元素本身。具有相同元素的两个 FS 是相等的并且具有相等的哈希值,因此满足 "dict identity" 的两个条件,换句话说,它们是相同的字典键:

>>> a = frozenset([1,1,1,1,2,3])
>>> b = frozenset([3,3,3,3,2,1])
>>> {a:1, b:2}
{frozenset([1, 2, 3]): 2}