Issue 21978: Support index access on OrderedDict views (e.g. o.keys()[7]) (original) (raw)

Implement __getitem__ on OrdredDict.keys, OrdredDict.values and OrdredDict.items, so the following code snippet wouldn't error:

>>> from collections import OrderedDict
>>> o = OrderedDict(((1, 2), (3, 4), (5, 6)))
>>> o
OrderedDict([(1, 2), (3, 4), (5, 6)])
>>> o.keys()
KeysView(OrderedDict([(1, 2), (3, 4), (5, 6)]))
>>> o.keys()[0]
Traceback (most recent call last):
  File "<string>", line 1, in <fragment>
builtins.TypeError: 'KeysView' object does not support indexing
>>> o.values()[0]
Traceback (most recent call last):
  File "<string>", line 1, in <fragment>
builtins.TypeError: 'ValuesView' object does not support indexing
>>> o.items()[0]
Traceback (most recent call last):
  File "<string>", line 1, in <fragment>
builtins.TypeError: 'ItemsView' object does not support indexing

I'm not sure this would make sense given that the ordered dict itself isn't indexable, given that keys/values/items on regular dicts aren't indexable, and given that keys/items views are set-like rather than sequence-like.

The one obvious way to get sequence behavior is to build a list:

s = list(od) s = list(od.values()) s = list(od.items())