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
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