Slicing a Python OrderedDict

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

    In Python 2, you can slice the keys:

    x.keys()[1:3]
    

    and to support both Python 2 and Python 3, you'd convert to a list first:

    list(k)[1:3]
    

    The Python 2 OrderedDict.keys() implementation does exactly that.

    In both cases you are given a list of keys in correct order. If creating a whole list first is an issue, you can use itertools.islice() and convert the iterable it produces to a list:

    from itertools import islice
    
    list(islice(x, 1, 3))
    

    All of the above also can be applied to the items; use dict.viewitems() in Python 2 to get the same iteration behaviour as Python 3 dict.items() provides. You can pass the islice() object straight to another OrderedDict() in this case:

    OrderedDict(islice(x.items(), 1, 3))  # x.viewitems() in Python 2
    

提交回复
热议问题