Python是否优化了字典查找?

时间:2014-11-17 19:20:43

标签: python dictionary

例如:

d = {"John": "Doe", "Paul": "Allen", "Bill": "Gates"}

只有想象这有几千个这样的名字,所有名字都是唯一的。

如果我想看看关键字“保罗”是否存在,它会在引擎盖下做什么?

2 个答案:

答案 0 :(得分:4)

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

来自Python Wiki

答案 1 :(得分:2)

Python字典使用哈希表实现。所以O(1)平均查找(取决于你的哈希函数的强度)。

参考文献: