概述
可以在 2017 Pycon 演讲Modern Python Dictionaries A confluence of a dozen great ideas 中找到有关如何实现 Python 字典的概述。
如何可视化减少
我了解哈希表将使用哈希函数将所有可能键的域减少到集合 m 并使用链接来解决冲突。 ...我似乎无法想象其中的 m 部分。
最简单的可视化是使用m == 2,以便散列将键分为两组:
>>> from pprint import pprint
>>> def hash(n):
'Hash a number into evens or odds'
return n % 2
>>> table = [[], []]
>>> for x in [10, 15, 12, 41, 80, 13, 40, 9]:
table[hash(x)].append(x)
>>> pprint(table, width=25)
[[10, 12, 80, 40],
[15, 41, 13, 9]]
在上面的例子中,八个键都被分为两组(偶数和赔率)。
该示例也适用于较大的 m 值,例如 m == 7:
>>> table = [[], [], [], [], [], [], []]
>>> for x in [10, 15, 12, 41, 80, 13, 40, 9]:
table[x % 7].append(x)
>>> pprint(table, width=25)
[[],
[15],
[9],
[10, 80],
[],
[12, 40],
[41, 13]]
如你所见,上面的例子有两个空槽和有碰撞的槽。
空字典的表
假设我在 python 中创建了一个空的 dict()。 python 是否会创建一个包含一些预定义数量的空条目的表?
是的,Python 为一个空表创建了八个槽。在 Python 的源代码中,我们在cpython/Objects/dictobject.c 中看到了#define PyDict_MINSIZE 8。