3.5. Typing Mapping

  • Before Python 3.9 you need from typing import Dict

  • Since Python 3.9: PEP 585 -- Type Hinting Generics In Standard Collections

  • Since Python 3.10: PEP 604 -- Allow writing union types as X | Y

3.5.1. Dict

Empty:

>>> data: dict = {}
>>> data: dict = dict()

Generic:

>>> data: dict = {'firstname': 'Mark', 'lastname': 'Watney'}

Strict:

>>> data: dict[str, str] = {'firstname': 'Mark', 'lastname': 'Watney'}
>>> data: dict[str, str|int] = {'firstname': 'Mark', 'lastname': 'Watney', 'age': 40}
>>>
>>> data: dict[int, str] = {
...    0: 'setosa',
...    1: 'virginica',
...    2: 'versicolor'}
>>>
>>> data: dict[float, str] = {
...    5.8: 'sepal_length',
...    2.7: 'sepal_width',
...    5.1: 'petal_length',
...    1.9: 'petal_width'}
>>>
>>> data: dict[str, float] = {
...    'sepal_length': 5.8,
...    'sepal_width': 2.7,
...    'petal_length': 5.1,
...    'petal_width': 1.9}

3.5.2. Use Case - 0x01

>>> calendarium: dict[int, str] = {
...     1961: 'Yuri Gagarin fly to space',
...     1969: 'Neil Armstrong set foot on the Moon',
... }

3.5.3. Use Case - 0x02

>>> calendarium: dict[int, list[str]] = {
...     1961: ['Yuri Gagarin fly to space', 'Alan Shepard fly to space'],
...     1969: ['Neil Armstrong set foot on the Moon'],
... }

3.5.4. Further Reading

  • More information in Type Annotations

  • More information in CI/CD Type Checking

3.5.5. Assignments

Code 3.36. Solution
"""
* Assignment: Typing Annotations Mapping
* Complexity: easy
* Lines of code: 3 lines
* Time: 2 min

English:
    1. Declare proper types for variables
    2. Run doctests - all must succeed

Polish:
    1. Zadeklaruj odpowiedni typ zmiennych
    2. Uruchom doctesty - wszystkie muszą się powieść

Tests:
    >>> import sys; sys.tracebacklimit = 0
    >>> from typing import get_type_hints
    >>> import importlib

    >>> module = importlib.import_module(__name__)
    >>> annotations = get_type_hints(module)

    >>> assert annotations['a'] == dict
    >>> assert annotations['b'] == dict[str, str]
    >>> assert annotations['c'] == dict[str, str | int]

    >>> assert a == {}, \
    'Do not modify variable `a` value, just add type annotation'
    >>> assert b == {'firstname': 'Mark', 'lastname': 'Watney'}, \
    'Do not modify variable `b` value, just add type annotation'
    >>> assert c == {'firstname': 'Mark', 'lastname': 'Watney', 'age': 40}, \
    'Do not modify variable `c` value, just add type annotation'
"""

# Declare proper types for variables
a: ... = {}
b: ... = {'firstname': 'Mark', 'lastname': 'Watney'}
c: ... = {'firstname': 'Mark', 'lastname': 'Watney', 'age': 40}