使用冻结集作为Dict键是否安全?

2024-05-11 22:56:47 发布

您现在位置:Python中文网/ 问答频道 /正文

很明显,它是有效的,但是是否有两组相同的元素碰巧在Dict中添加了两个条目的情况?我想我之前遇到过这种情况,并将代码从frozenset(...)更改为tuple(sorted(frozenset(...)))。知道Dict和frozenset实现方式的人能确认是否需要这样做吗?


Tags: 代码目的元素方式情况dictsortedtuple
3条回答

使用frozenset作为dict键是否安全?是的。

根据文档,Frozenset是散列的,因为它是不可变的。这意味着它可以用作dict的密钥,因为密钥的先决条件是它是散列的。

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?

不,^{} hashing algorithm不依赖于元素的顺序,只依赖于元素本身。具有相同元素的两个FS是相等的并且具有相等的散列,因此满足“dict identity”的两个条件,换句话说,它们是相同的dict key:

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

相关问题 更多 >