Skip to content Skip to sidebar Skip to footer

Why Do Dict_items Objects Not Support Indexing?

I know that you can cast dict_items into a list to allow item indexing. But I do not know why this operation is not allowed directly. Is it because dict_items objects are generator

Solution 1:

dict_items do not support indexing because these objects are intended to be set-like, and sets do not support indexing.

They do quack like sets in other ways:

>>> d1 = {'k1': 'v1', 'k2': 'v2', 'k3': 'v3'}
>>> d2 = {'k2': 'v2', 'k3': 'not v3'}
>>> d1.items() & d2.items()
{('k2', 'v2')}
>>> d1.items() | d2.items()
{('k1', 'v1'), ('k2', 'v2'), ('k3', 'not v3'), ('k3', 'v3')}

If any value is not hashable, you lose the ability to treat the dict items views with set operations.

It is not sensible to give indexing support to dict_items views, because the dict does not have an ordering until Python 3.7+, so accessing "the 0th" item would not be well-defined. Even in Python 3.7, where there is a sensible ordering to use for indexing (i.e. the insertion order), it is non-trivial to implement this with O(1) complexity, so it's not supported. The "unwritten rule" is that indexing should be constant-time operation (as it is for list, tuple, dict, str - see here).

Post a Comment for "Why Do Dict_items Objects Not Support Indexing?"