Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 generators? If so, when I'm seeing

>>> {"foo": "bar", "baz": "qux"}.items()
dict_items([('foo', 'bar'), ('baz', 'qux')]) 

is Python evaluating my generator when repr is called?

like image 645
ohe Avatar asked Oct 19 '18 21:10

ohe


People also ask

What is a Dict_items object?

The dict. items() returns a dictionary view object that provides a dynamic view of dictionary elements as a list of key-value pairs. This view object changes when the dictionary changes.

What is dict_keys object?

The keys() method outputs a dict_keys object that presents a list of a dictionary's keys.

Is Dict_values a list?

In Python 3 the dict. values() method returns a dictionary view object, not a list like it does in Python 2.

What does .keys do in Python?

keys() method in Python is used to retrieve all of the keys from the dictionary. The keys must be of an immutable type (string, number, or tuple with immutable elements) and must be unique.


1 Answers

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

like image 152
wim Avatar answered Sep 27 '22 21:09

wim