6.5. Mapping Items

  • Key-Value Pairs

6.5.1. Get Key-Value Pairs

In Python 2, the methods items(), keys() and values() used to "take a snapshot" of the dictionary contents and return it as a list. It meant that if the dictionary changed while you were iterating over the list, the contents in the list would not change. In Python 3, these methods return a view object whose contents change dynamically as the dictionary changes. Therefore, in order for the behavior of iterations over the result of these methods to remain consistent with previous versions, an additional call to ``list()` has to be performed in Python 3 to "take a snapshot" of the view object contents 1.

>>> crew = {
...    'commander': 'Melissa Lewis',
...    'botanist': 'Mark Watney',
...    'pilot': 'Rick Martinez',
... }
>>> crew.items()
dict_items([('commander', 'Melissa Lewis'), ('botanist', 'Mark Watney'), ('pilot', 'Rick Martinez')])
>>> list(crew.items())  
[('commander', 'Melissa Lewis'),
 ('botanist', 'Mark Watney'),
 ('pilot', 'Rick Martinez')]

6.5.2. References


Frédéric Hamidi. Why does Python 3 need dict.items to be wrapped with list()? Retrieved: 2021-02-28. URL: https://stackoverflow.com/a/17695716

6.5.3. Assignments

Code 6.3. Solution
* Assignment: Mapping Items List
* Required: yes
* Complexity: easy
* Lines of code: 1 lines
* Time: 2 min

    3. Define `result: list[tuple]` with list of `DATA` key-value pairs
    4. Run doctests - all must succeed

    3. Zdefiniuj `result: list[tuple]` z listą par klucz-wartość z `DATA`
    4. Uruchom doctesty - wszystkie muszą się powieść

    * `list()`
    * `dict.items()`

    >>> import sys; sys.tracebacklimit = 0

    >>> assert type(result) is list, \
    'Variable `result` has invalid type, should be list'
    >>> assert all(type(x) is tuple for x in result), \
    'All rows in `result` should be tuples'

    >>> result  # doctest: +NORMALIZE_WHITESPACE
    [('Sepal length', 5.8),
     ('Sepal width', 2.7),
     ('Petal length', 5.1),
     ('Petal width', 1.9)]

DATA = {'Sepal length': 5.8,
        'Sepal width': 2.7,
        'Petal length': 5.1,
        'Petal width': 1.9}

# List with key-value pairs from DATA
# type: list[tuple]
result = ...