例如:
d = {"John": "Doe", "Paul": "Allen", "Bill": "Gates"}
想象一下,如果有几千万个这样的名字,所有名字都是以名字为唯一标识。
如果我想查看键 "Paul" 是否存在,那么它在底层执行了什么操作?
例如:
d = {"John": "Doe", "Paul": "Allen", "Bill": "Gates"}
想象一下,如果有几千万个这样的名字,所有名字都是以名字为唯一标识。
如果我想查看键 "Paul" 是否存在,那么它在底层执行了什么操作?
Python的字典实现通过要求键对象提供“哈希”函数,将字典查找的平均复杂度降低到O(1)。这样的哈希函数获取键对象中的信息,并使用它生成一个整数,称为哈希值。然后使用此哈希值来确定应将此(键,值)对放置在哪个“桶”中。此查找功能的伪代码可能如下所示:
def lookup(d, key):
'''dictionary lookup is done in three steps:
1. A hash value of the key is computed using a hash function.
2. The hash value addresses a location in d.data which is
supposed to be an array of "buckets" or "collision lists"
which contain the (key,value) pairs.
3. The collision list addressed by the hash value is searched
sequentially until a pair is found with pair[0] == key. The
return value of the lookup is then pair[1].
'''
h = hash(key) # step 1
cl = d.data[h] # step 2
for pair in cl: # step 3
if key == pair[0]:
return pair[1]
else:
raise KeyError, "Key %s not found." % key
From the Python Wiki