11.5. For Dict

11.5.1. Iterate Keys

  • Suggested variable name: key

>>> data = {
...     'firstname': 'Mark',
...     'lastname': 'Watney',
...     'username': 'mwatney',
... }
>>>
>>> for key in data.keys():
...     print(f'{key=}')
...
key='firstname'
key='lastname'
key='username'

11.5.2. Iterate Values

  • Suggested variable name: value

>>> data = {
...     'firstname': 'Mark',
...     'lastname': 'Watney',
...     'username': 'mwatney',
... }
>>>
>>> for value in data.values():
...     print(f'{value=}')
...
value='Mark'
value='Watney'
value='mwatney'

11.5.3. Iterate Items

  • Items - key-value pairs

  • Suggested variable name: item or key, value

>>> data = {
...     'firstname': 'Mark',
...     'lastname': 'Watney',
...     'username': 'mwatney',
... }
>>>
>>> for item in data.items():
...     print(f'{item=}')
...
item=('firstname', 'Mark')
item=('lastname', 'Watney')
item=('username', 'mwatney')

You can use unpacking:

>>> data = {
...     'firstname': 'Mark',
...     'lastname': 'Watney',
...     'username': 'mwatney',
... }
>>>
>>> for key, value in data.items():
...     print(f'{key=}, {value=}')
...
key='firstname', value='Mark'
key='lastname', value='Watney'
key='username', value='mwatney'

11.5.4. Iterate Dict

  • By default dict iterates over keys

  • Suggested variable name: key

>>> data = {
...     'firstname': 'Mark',
...     'lastname': 'Watney',
...     'username': 'mwatney',
... }
>>>
>>> for element in data:
...     print(f'{element=}')
...
element='firstname'
element='lastname'
element='username'

11.5.5. 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: For Dict Keys
# - Difficulty: easy
# - Lines: 3
# - Minutes: 2

# %% English
# 1. Iterate over `DATA` and collect keys in `result: list[str]`
# 2. Use `dict.keys()`
# 3. Run doctests - all must succeed

# %% Polish
# 1. Iteruj po `DATA` i zbierz klucze w `result: list[str]`
# 2. Użyj `dict.keys()`
# 3. Uruchom doctesty - wszystkie muszą się powieść

# %% Hints
# - `dict.keys()`

# %% Tests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'

>>> assert result is not Ellipsis, \
'Assign your result to variable `result`'
>>> assert type(result) is list, \
'Variable `result` has invalid type, should be list'

>>> assert all(type(x) is str for x in result)
>>> assert len(result) == 3

>>> from pprint import pprint
>>> pprint(result)
['firstname', 'lastname', 'username']
"""

DATA = {
    'firstname': 'Mark',
    'lastname': 'Watney',
    'username': 'mwatney',
}

# Iterate over `DATA` and collect keys in `result: list[str]`
# Use `dict.keys()`
# type: list[str]
result = ...


# %% 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: For Dict Values
# - Difficulty: easy
# - Lines: 3
# - Minutes: 2

# %% English
# 1. Iterate over `DATA` and collect values in `result: list[str]`
# 2. Use `dict.values()`
# 3. Run doctests - all must succeed

# %% Polish
# 1. Iteruj po `DATA` i zbierz wartości w `result: list[str]`
# 2. Użyj `dict.values()`
# 3. Uruchom doctesty - wszystkie muszą się powieść

# %% Hints
# - `dict.values()`

# %% Tests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'

>>> assert result is not Ellipsis, \
'Assign your result to variable `result`'
>>> assert type(result) is list, \
'Variable `result` has invalid type, should be list'

>>> assert all(type(x) is str for x in result)
>>> assert len(result) == 3

>>> from pprint import pprint
>>> pprint(result)
['Mark', 'Watney', 'mwatney']
"""

DATA = {
    'firstname': 'Mark',
    'lastname': 'Watney',
    'username': 'mwatney',
}

# Iterate over `DATA` and collect values in `result: list[str]`
# Use `dict.values()`
# type: list[str]
result = ...


# %% 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: For Dict Items
# - Difficulty: easy
# - Lines: 3
# - Minutes: 2

# %% English
# 1. Iterate over `DATA` and collect key-value pairs in `result: list[str]`
# 2. Use `dict.items()`
# 3. Do not use unpacking
# 4. Run doctests - all must succeed

# %% Polish
# 1. Iteruj po `DATA` i zbierz pary klucz-wartość w `result: list[str]`
# 2. Użyj `dict.items()`
# 3. Nie używaj rozpakowania
# 4. Uruchom doctesty - wszystkie muszą się powieść

# %% Hints
# - `dict.values()`

# %% Tests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'

>>> assert result is not Ellipsis, \
'Assign your result to variable `result`'
>>> assert type(result) is list, \
'Variable `result` has invalid type, should be list'

>>> assert all(type(x) is tuple for x in result)
>>> assert len(result) == 3

>>> from pprint import pprint
>>> pprint(result, width=30)
[('firstname', 'Mark'),
 ('lastname', 'Watney'),
 ('username', 'mwatney')]
"""

DATA = {
    'firstname': 'Mark',
    'lastname': 'Watney',
    'username': 'mwatney',
}

# Iterate over `DATA` and collect key-value pairs in `result: list[str]`
# Use `dict.items()`
# Do not use unpacking
# type: list[str]
result = ...


# %% 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: For Dict Unpacking
# - Difficulty: easy
# - Lines: 3
# - Minutes: 2

# %% English
# 1. Iterate over `DATA` and collect key-value pairs in `result: list[str]`
# 2. Use `dict.items()`
# 3. Use unpacking
# 4. Run doctests - all must succeed

# %% Polish
# 1. Iteruj po `DATA` i zbierz pary klucz-wartość w `result: list[str]`
# 2. Użyj `dict.items()`
# 3. Użyj rozpakowania
# 4. Uruchom doctesty - wszystkie muszą się powieść

# %% Hints
# - `dict.values()`

# %% Tests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'

>>> assert result is not Ellipsis, \
'Assign your result to variable `result`'
>>> assert type(result) is list, \
'Variable `result` has invalid type, should be list'

>>> assert all(type(x) is tuple for x in result)
>>> assert len(result) == 3

>>> from pprint import pprint
>>> pprint(result, width=30)
[('firstname', 'Mark'),
 ('lastname', 'Watney'),
 ('username', 'mwatney')]
"""

DATA = {
    'firstname': 'Mark',
    'lastname': 'Watney',
    'username': 'mwatney',
}

# Iterate over `DATA` and collect key-value pairs in `result: list[str]`
# Use `dict.items()`
# Use unpacking
# type: list[str]
result = ...


# %% 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: For Dict Default
# - Difficulty: easy
# - Lines: 3
# - Minutes: 2

# %% English
# 1. Iterate over `DATA` and collect element in `result: list[str]`
# 2. Do not use `dict.keys()`
# 3. Run doctests - all must succeed

# %% Polish
# 1. Iteruj po `DATA` i zbierz elementy w `result: list[str]`
# 2. Nie używaj `dict.keys()`
# 3. Uruchom doctesty - wszystkie muszą się powieść

# %% Tests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'

>>> assert result is not Ellipsis, \
'Assign your result to variable `result`'
>>> assert type(result) is list, \
'Variable `result` has invalid type, should be list'

>>> assert all(type(x) is str for x in result)
>>> assert len(result) == 3

>>> from pprint import pprint
>>> pprint(result)
['firstname', 'lastname', 'username']
"""

DATA = {
    'firstname': 'Mark',
    'lastname': 'Watney',
    'username': 'mwatney',
}

# Iterate over `DATA` and collect keys in `result: list[str]`
# Do not use `dict.keys()`
# type: list[str]
result = ...


# %% 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: For Dict Swap
# - Difficulty: easy
# - Lines: 3
# - Minutes: 5

# %% English
# 1. Reverse dict (swap keys and values)
# 2. Run doctests - all must succeed

# %% Polish
# 1. Odwróć dict (zamień klucze z wartościami)
# 2. Uruchom doctesty - wszystkie muszą się powieść

# %% Hints
# - `dict.items()`

# %% Tests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'

>>> assert result is not Ellipsis, \
'Assign your result to variable `result`'
>>> assert type(result) is dict, \
'Variable `result` has invalid type, should be dict'

>>> assert all(type(x) is str for x in result.keys())
>>> assert all(type(x) is int for x in result.values())
>>> assert len(result.keys()) == 3

>>> assert 'virginica' in result.keys()
>>> assert 'setosa' in result.keys()
>>> assert 'versicolor' in result.keys()

>>> assert 0 in result.values()
>>> assert 1 in result.values()
>>> assert 2 in result.values()

>>> from pprint import pprint
>>> pprint(result, width=20, sort_dicts=False)
{'virginica': 0,
 'setosa': 1,
 'versicolor': 2}
"""

DATA = {
    0: 'virginica',
    1: 'setosa',
    2: 'versicolor',
}

# Reverse dict (swap keys and values)
# type: dict[str,int]
result = ...


# %% 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: For Dict Endswith
# - Difficulty: medium
# - Lines: 6
# - Minutes: 5

# %% English
# 1. Define `result: list[str]`
# 2. Collect in `result` all email addresses from `DATA` -> `crew`
#    with domain names mentioned in `DOMAINS`
# 3. Run doctests - all must succeed

# %% Polish
# 1. Zdefiniuj `result: list[str]`
# 2. Zbierz w `result` wszystkie adresy email z `DATA` -> `crew`
#    z nazwami domenowymi wymienionymi w `DOMAINS`
# 3. Uruchom doctesty - wszystkie muszą się powieść

# %% Why
# - Check if you can filter data
# - Check if you know string methods
# - Check if you know how to iterate over `list[dict]`

# %% Hints
# - `str.split()`
# - `list.append()`
# - `... in ...`

# %% Tests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'

>>> from pprint import pprint

>>> assert result is not Ellipsis, \
'Assign result to variable: `result`'
>>> assert type(result) is list, \
'Result must be a list'
>>> assert len(result) > 0, \
'Result cannot be empty'
>>> assert all(type(element) is str for element in result), \
'All elements in result must be a str'

>>> result = sorted(result)
>>> pprint(result)
['avogel@esa.int',
 'bjohanssen@nasa.gov',
 'cbeck@nasa.gov',
 'mlewis@nasa.gov',
 'mwatney@nasa.gov',
 'rmartinez@nasa.gov']
"""

DATA = {
    'group': 'staff',
    'created': '2000-01-02',
    'modified': '2000-01-05',
    'users': [
        {'name': 'Mark Watney', 'email': 'mwatney@nasa.gov'},
        {'name': 'Melissa Lewis', 'email': 'mlewis@nasa.gov'},
        {'name': 'Rick Martinez', 'email': 'rmartinez@nasa.gov'},
        {'name': 'Pan Twardowski', 'email': 'ptwardowski@polsa.gov.pl'},
        {'name': 'Alex Vogel', 'email': 'avogel@esa.int'},
        {'name': 'Chris Beck', 'email': 'cbeck@nasa.gov'},
        {'name': 'Ivan Ivanovich', 'email': 'iivanovich@roscosmos.ru'},
        {'name': 'Beth Johanssen', 'email': 'bjohanssen@nasa.gov'},
]}

DOMAINS = ('esa.int', 'nasa.gov')

# Email addresses with top-level domain in DOMAINS
# type: list[str]
result = ...