且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Python 字典是哈希表的一个例子吗?

更新时间:2023-11-26 18:55:16

没错,就是哈希映射或者哈希表.您可以阅读 Tim Peters 所写的关于 python dict 实现的描述,此处.

这就是为什么你不能使用不可哈希"的东西作为字典键,比如列表:

>>>a = {}>>>b = ['一些','列表']>>>哈希(b)回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 <module> 中类型错误:列表对象不可散列>>>a[b] = '一些'回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 <module> 中类型错误:列表对象不可散列

您可以阅读有关哈希表的更多信息检查它是如何在 python 中实现的 和 为什么它是这样实现的.

One of the basic data structures in Python is the dictionary, which allows one to record "keys" for looking up "values" of any type. Is this implemented internally as a hash table? If not, what is it?

Yes, it is a hash mapping or hash table. You can read a description of python's dict implementation, as written by Tim Peters, here.

That's why you can't use something 'not hashable' as a dict key, like a list:

>>> a = {}
>>> b = ['some', 'list']
>>> hash(b)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: list objects are unhashable
>>> a[b] = 'some'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: list objects are unhashable

You can read more about hash tables or check how it has been implemented in python and why it is implemented that way.