pythonpython-3.xdictview

Why are `dict_keys`, `dict_values`, and `dict_items` not subscriptable?


Referring to an item of a dict_keys, dict_values, or dict_items object by index raises a type error. For example:

> my_dict = {"foo": 0, "bar": 1, "baz": 2}
> my_dict.items()[0]
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
----> 1 my_dict.items()[0]

TypeError: 'dict_items' object is not subscriptable

My question is not how to address this. I am aware that one can just call list() or tuple() on a dict_keys, dict_values, or dict_items object and then subscript that.

My question is why does this behaviour still persist in python given that the order of items in a dictionary has been guaranteed since python 3.7.0. Why is it not possible (or not desirable) to refactor the dict_keys, dict_values, and dict_items types so that they are subscriptable?

The documentation for the stdlib describes these types as "view objects". I imagine that is where the answer to my question lies but I can't find a more detailed description of what a "view object" actually is. Can anyone enlighten me on this matter as well?


Solution

  • "Ordered" doesn't mean "efficiently indexable". There is no more efficient way to retrieve the Nth item of a dict view than to iterate N steps.

    Allowing indexing would give the impression that views can support this operation efficiently, which would in turn encourage extremely inefficient code. Trying to change the implementation so indexing is efficient would make other dict operations much less efficient, which isn't worthwhile for the use cases dicts are actually designed for.