[Tutor] Why is an OrderedDict not sliceable?
Oscar Benjamin
oscar.j.benjamin at gmail.com
Thu Jan 21 06:02:40 EST 2016
On 21 January 2016 at 09:19, Ben Finney <ben+python at benfinney.id.au> wrote:
> Albert-Jan Roskam <sjeik_appie at hotmail.com> writes:
>
>> Why is an OrderedDict not sliceable?
>
> Because slicing implies index access. The built-in ‘dict’ and
> ‘collections.OrderedDict’ both do not support indexed access::
According to a narrow definition of indexed access. I would say that
d[k] is index access even if d is a dict and k a key.
Albert-Jan I guess what you want is this:
from collections import OrderedDict
class SliceableOrderedDict(OrderedDict):
def __getitem__(self, sl):
if isinstance(sl, slice):
keys = list(self)
keyslice = slice(
None if sl.start is None else keys.index(sl.start),
None if sl.stop is None else keys.index(sl.stop),
sl.step
)
newitems = ((k, self[k]) for k in keys[keyslice])
return SliceableOrderedDict(newitems)
else:
return super().__getitem__(sl)
I guess that the authors of OrderedDict just didn't really consider
this to be very useful. Apart from having ordered iteration
OrderedDict is not really that deeply thought out. There's a thread on
python-ideas about the inconsistent behaviour of the keys and values
views and equality comparison of OrderedDicts on python-ideas at the
moment:
https://mail.python.org/pipermail/python-ideas/2015-December/037472.html
--
Oscar
More information about the Tutor
mailing list