[Tutor] Why is an OrderedDict not sliceable?
Albert-Jan Roskam
sjeik_appie at hotmail.com
Thu Jan 21 04:02:29 EST 2016
> Date: Thu, 21 Jan 2016 12:00:29 +1100
> From: steve at pearwood.info
> To: tutor at python.org
> Subject: Re: [Tutor] Why is an OrderedDict not sliceable?
>
> On Wed, Jan 20, 2016 at 01:33:17PM +0000, Albert-Jan Roskam wrote:
> > Hi,
> >
> > Like the subject says: Why is an OrderedDict not sliceable? (From the
> > collections library). Was that an intentional omission, or a mistake?
> > [1]
>
> Because slicing a dict makes no sense. A dict is a mapping, not a
> sequence.
For a regular dict: yes, I agree that doesn't make sense, because a regular dict is unordered.
A collections.OrderedDict on the other hand..
> d = OrderedDict()
> d["cow"] = "a"
> d["fox"] = "b"
> d["ape"] = "c"
> d["dog"] = "d"
> d["bee"] = "e"
>
> I can do a dict lookup on a key:
>
> d["cow"]
>
> What would a slice even mean? d[1:4] but 1, 2, 3 are not keys of the
> dict.
Indexing would create ambiguity, e.g d[1] might mean
* return the value associated with key 1
* return the first value
But that's not true for slices, because they cannot be dictionary keys anyway:
>>> {slice(1, 2): None}
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type
With islice it is easy to do it anyway, but I still find it strange that OrderedDict.__getitem__ does not do that already (sorry!)
>>> from itertools import islice
>>> from collections import OrderedDict
>>> od = OrderedDict({"a": 1, "b": 2})
>>> list(islice(od, 1, 2))
['b']
More information about the Tutor
mailing list