Slicing a Python OrderedDict

后端 未结 6 1236
别那么骄傲
别那么骄傲 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:10

    You can use the itertools.islice function, which takes an iterable and outputs the stop first elements. This is beneficial since iterables don't support the common slicing method, and you won't need to create the whole items list from the OrderedDict.

    from collections import OrderedDict
    from itertools import islice
    o = OrderedDict([('a', 1), ('b', 2), ('c', 3), ('d', 4)])
    sliced = islice(o.iteritems(), 3)  # o.iteritems() is o.items() in Python 3
    sliced_o = OrderedDict(sliced)
    

提交回复
热议问题