[Tutor] Why is an OrderedDict not sliceable?

Albert-Jan Roskam sjeik_appie at hotmail.com
Sun Jan 24 15:29:00 EST 2016


> From: oscar.j.benjamin at gmail.com
> Date: Thu, 21 Jan 2016 11:02:40 +0000
> To: ben+python at benfinney.id.au
> Subject: Re: [Tutor] Why is an OrderedDict not sliceable?
> CC: tutor at python.org
> 
> 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)
 
 
That looks interesting. I will check this out tomorrow at work. If I read it correctly this is indeed exactly what I meant. Thank you!!

 
> 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

As I said in a prior email: That is SCARY! Should I just avoid OrderedDict like the plague?
 

> --
> Oscar
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor

 		 	   		  


More information about the Tutor mailing list