[Tutor] Why is an OrderedDict not sliceable?

Ben Finney ben+python at benfinney.id.au
Thu Jan 21 04:19:20 EST 2016


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

    >>> import collections
    >>> foo = collections.OrderedDict([
    ...         ('a', 1), ('b', 2), ('c', 3), ('d', 4)])
    >>> foo[3]
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    KeyError: 3

    >>> bar = dict([
    ...         ('a', 1), ('b', 2), ('c', 3), ('d', 4)])
    >>> bar[3]
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    KeyError: 3

Index access with ‘foo[index]’ syntax, and slicing with
‘foo[start_index:stop_index:step]’ syntax, collide with the existing
key-access meaning of ‘foo[key]’ for a mapping.

-- 
 \      “[I]t is impossible for anyone to begin to learn that which he |
  `\                thinks he already knows.” —Epictetus, _Discourses_ |
_o__)                                                                  |
Ben Finney



More information about the Tutor mailing list