Home  >  Q&A  >  body text

Python遍历dict的key最高效的方法是什么?

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

阿神阿神2759 days ago723

reply all(2)I'll reply

  • PHPz

    PHPz2017-04-17 14:32:50

    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

    reply
    0
  • 高洛峰

    高洛峰2017-04-17 14:32:50

    for key in _dict:
        pass
    

    reply
    0
  • Cancelreply