Why do dict_items objects not support indexing?

后端 未结 1 950
孤街浪徒
孤街浪徒 2021-01-17 16:25

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

1条回答
  •  孤街浪徒
    2021-01-17 16:37

    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).

    0 讨论(0)
提交回复
热议问题