使用冻结集作为Dict键是否安全? [英] Is it safe to use frozen set as Dict key?

查看:128
本文介绍了使用冻结集作为Dict键是否安全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

It obviously works but are there cases where two sets of same elements happen to add two entries in Dict? I guess I got this condition earlier and changed my code from frozenset(...) to tuple(sorted(frozenset(...))). Can someone who knows how Dict and frozenset implementation confirm if that is required or not?

推荐答案

在某些情况下,两组相同的元素碰巧在Dict中添加了两个条目吗?

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

不. frozenset哈希算法不取决于元素的顺序,仅取决于元素本身.具有相同元素的两个FS相等且具有相等的散列,因此满足字典身份"的两个标准,换言之,它们是相同的字典键:

No. frozenset hashing algorithm doesn't depend on the order of the elements, only on elements themselves. Two FS'es with the same elements are equal and have equal hashes, thus satisfying both criteria for "dict identity", in other words, they are the same 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}

这篇关于使用冻结集作为Dict键是否安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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