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?
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.
The keys() method outputs a dict_keys object that presents a list of a dictionary's keys.
In Python 3 the dict. values() method returns a dictionary view object, not a list like it does in Python 2.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With