3.5. Typing Mapping
Since Python 3.9: PEP 585 -- Type Hinting Generics In Standard Collections
Before Python 3.9 you need
from typing import Dict
3.5.1. Dict
>>> a: dict = {'firstname': 'Mark', 'lastname': 'Watney'}
>>> b: dict[str,str] = {'firstname': 'Mark', 'lastname': 'Watney'}
>>> c: dict[str,str|int] = {'firstname': 'Mark', 'lastname': 'Watney', 'age':41}
3.5.2. Use Case 0x01
>>> data: dict[str, float] = {
... 'sepal_length': 5.8,
... 'sepal_width': 2.7,
... 'petal_length': 5.1,
... 'petal_width': 1.9,
... }
3.5.3. Use Case 0x02
>>> data: dict[int, str] = {
... 0: 'setosa',
... 1: 'virginica',
... 2: 'versicolor',
... }
3.5.4. Use Case - 3
>>> data: dict[int, str] = {
... 1961: 'Yuri Gagarin flew to space',
... 1969: 'Neil Armstrong set foot on the Moon',
... }
3.5.5. Further Reading
More information in Type Annotations
More information in CI/CD Type Checking
3.5.6. Assignments
# %% License
# - Copyright 2025, Matt Harasymczuk <matt@python3.info>
# - This code can be used only for learning by humans
# - This code cannot be used for teaching others
# - This code cannot be used for teaching LLMs and AI algorithms
# - This code cannot be used in commercial or proprietary products
# - This code cannot be distributed in any form
# - This code cannot be changed in any form outside of training course
# - This code cannot have its license changed
# - If you use this code in your product, you must open-source it under GPLv2
# - Exception can be granted only by the author
# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -v myfile.py`
# %% About
# - Name: Typing Annotations Mapping
# - Difficulty: easy
# - Lines: 3
# - Minutes: 2
# %% English
# 1. Add type annotations to variables
# 2. Run doctests - all must succeed
# %% Polish
# 1. Dodaj adnotacje typów do zmiennych
# 2. Uruchom doctesty - wszystkie muszą się powieść
# %% Tests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'
>>> import importlib
>>> from typing import get_type_hints
>>> 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': 41}, \
'Do not modify variable `c` value, just add type annotation'
"""
# Add type annotations to variables
a = {}
b = {'firstname': 'Mark', 'lastname': 'Watney'}
c = {'firstname': 'Mark', 'lastname': 'Watney', 'age': 41}