python字典实现关键字检索_python字典的索引快速搜索方法比较

闲话少叙,python中经常会对字典的索引进行搜索判断,如判断‘user’是否为{'user1':'New Student','user2':'Old student'}的索引,本文总结了5种方法进行索引的搜索,并比较了运行时间。

五种方法有:

① index in dict.keys()

② dict.has_key(index)

③ index in dict

④ index in set(dict)

⑤ index in set(dict.keys())

先构建一个程序运行时间的函数,用于测试。

from time import clock as now

def costTime(f, testDict, num, describe):

start =

now()

f(testDict,

num)

finish =

now()

return 'The

costing time of %s is %f' % (describe, finish - start)

然后分别写出五个函数:

#测试dict.keys()

def test_dictKeys(testDict, num):

for i in

range(num):

if i in testDict.keys():

testDict[i]

#测试dict.has_key()

def test_has_key(testDict, num):

for i in

<

你可能感兴趣的:(python字典实现关键字检索)