Accessing items in an collections.OrderedDict by index

后端 未结 9 1585
我寻月下人不归
我寻月下人不归 2020-11-28 19:41

Lets say I have the following code:

import collections
d = collections.OrderedDict()
d[\'foo\'] = \'python\'
d[\'bar\'] = \'spam\'

Is there

9条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-28 20:35

    It is dramatically more efficient to use IndexedOrderedDict from the indexed package.

    Following Niklas's comment, I have done a benchmark on OrderedDict and IndexedOrderedDict with 1000 entries.

    In [1]: from numpy import *
    In [2]: from indexed import IndexedOrderedDict
    In [3]: id=IndexedOrderedDict(zip(arange(1000),random.random(1000)))
    In [4]: timeit id.keys()[56]
    1000000 loops, best of 3: 969 ns per loop
    
    In [8]: from collections import OrderedDict
    In [9]: od=OrderedDict(zip(arange(1000),random.random(1000)))
    In [10]: timeit od.keys()[56]
    10000 loops, best of 3: 104 µs per loop
    

    IndexedOrderedDict is ~100 times faster in indexing elements at specific position in this specific case.

提交回复
热议问题