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

6.5.3. Assignments

Code 6.3. Solution
"""
* Assignment: Mapping Items List
* Type: class assignment
* Complexity: easy
* Lines of code: 1 lines
* Time: 2 min

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

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

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

Tests:
    >>> 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 = ...