Python遍历dict的key最高效的方法是什么?
阿神
阿神 2017-04-17 14:30:50
0
2
740

昨天被人问起的,非常惭愧,写了两年Python还以为keys()就是最高效的遍历方法。

阿神
阿神

闭关修行中......

reply all(2)
PHPzhong

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)

Output
54.1994677764
30.2660675759
31.3075812315

is the result of windows + python 2.7

小葫芦
for key in _dict:
    pass
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template