Slicing a Python OrderedDict

后端 未结 6 1252
别那么骄傲
别那么骄傲 2020-12-15 19:48

In my code I frequently need to take a subset range of keys+values from a Python OrderedDict (from collections package). Slicing doesn\'t work (throws Typ

6条回答
  •  一个人的身影
    2020-12-15 20:03

    I wanted to slice using a key, since I didn't know the index in advance:

    o = OrderedDict(zip(list('abcdefghijklmnopqrstuvwxyz'),range(1,27)))
    
    stop = o.keys().index('e')           # -> 4
    OrderedDict(islice(o.items(),stop))  # -> OrderedDict([('a', 1), ('b', 2), ('c', 3)])
    

    or to slice from start to stop:

    start = o.keys().index('c')                    # -> 2
    stop = o.keys().index('e')                     # -> 4
    OrderedDict(islice(o.iteritems(),start,stop))  # -> OrderedDict([('c', 3), ('d', 4)])
    

提交回复
热议问题