获取字典密钥哈希而无需重新计算 [英] Get dictionary keys hashes without recalculation
问题描述
是否有一种方法可以从字典中提取现有的密钥散列,而无需再次重新计算它们?
Is there a way to extract existing key hashes from a dictionary, without recalculating them again?
通过散列而不是密钥来公开字典并暴露其风险是什么?
What would be the risks for exposing them and consequntly, accessing the dict by hashes not keys?
推荐答案
Python dict
的密钥必须为 hashable ,即实现__hash__
特殊方法(以及与您的问题无关的其他一些方法),或者是某些预定的内置类型之一.因此,您实际上可以在没有表的情况下访问键的哈希值,例如,通过
A Python dict
's keys must be hashable, i.e., implement the __hash__
special method (as well as some other methods irrelevant to your question), or be one of some predetermined built in types. So you actually can access the hash value of a key without the table, e.g., through
>>> '123'.__hash__()
163512108404620371
或更统一地
>>> hash('123')
163512108404620371
>>> hash(2)
2
正如评论所指出的那样,哈希值和表中的位置不是一回事.实际上,当表调整大小时,键的哈希值将保持不变,但是位置可能会改变.因此,为:
That being said, as noted by the comments, a hash value and a position in a table are not the same thing. In fact, as a table resizes, the hash value of a key will remain the same, but the position might change. Consequently, as:
-
通过
hash()
该位置将暴露字典的内部状态
the position would expose the dictionary's internal state
您可以通过__hash__
方法
暴露按键的位置可能毫无意义.
there is probably no point in exposing the keys' positions.
这篇关于获取字典密钥哈希而无需重新计算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!