Because keys() needs to form a list, building a list is very expensive for a large dict. What lihsing said is right, and there is another way to write it, iterkeys(), which has little speed difference.
See test code
import timeit
DICT_SIZE = 100*10000
testDict = dict()
for i in range(DICT_SIZE):
testDict[i] = i # 构建大小为100W的字典
assert len(testDict) == DICT_SIZE
def test1():
for _ in testDict.keys():
pass
def test2():
for _ in testDict:
pass
def test3():
for _ in testDict.iterkeys():
pass
# 分别测试2K次
print timeit.timeit("test1()", setup="from __main__ import test1", number=2000)
print timeit.timeit("test2()", setup="from __main__ import test2", number=2000)
print timeit.timeit("test3()", setup="from __main__ import test3", number=2000)
Because keys() needs to form a list, building a list is very expensive for a large dict. What lihsing said is right, and there is another way to write it, iterkeys(), which has little speed difference.
See test code
Output
54.1994677764
30.2660675759
31.3075812315
is the result of windows + python 2.7