12.5. For Dict
Iterate Keys
Iterate Values
Iterate Items - key-value pairs
By default
dict
iterates over keys
12.5.1. Iterate Keys
Suggested variable name:
key
>>> data = {
... 'firstname': 'Alice',
... 'lastname': 'Apricot',
... }
>>>
>>> for key in data.keys():
... print(f'{key=}')
...
key='firstname'
key='lastname'
12.5.2. Iterate Values
Suggested variable name:
value
>>> data = {
... 'firstname': 'Alice',
... 'lastname': 'Apricot',
... }
>>>
>>> for value in data.values():
... print(f'{value=}')
...
value='Alice'
value='Apricot'
12.5.3. Iterate Items
Iterate Items - key-value pairs
Suggested variable name:
item
orkey
,value
>>> data = {
... 'firstname': 'Alice',
... 'lastname': 'Apricot',
... }
>>>
>>> for item in data.items():
... print(f'{item=}')
...
item=('firstname', 'Alice')
item=('lastname', 'Apricot')
You can use unpacking:
>>> data = {
... 'firstname': 'Alice',
... 'lastname': 'Apricot',
... }
>>>
>>> for key, value in data.items():
... print(f'{key=}, {value=}')
...
key='firstname', value='Alice'
key='lastname', value='Apricot'
12.5.4. Iterate Dict
By default
dict
iterates over keysSuggested variable name:
key
>>> data = {
... 'firstname': 'Alice',
... 'lastname': 'Apricot',
... }
>>>
>>> for default in data:
... print(f'{default=}')
...
default='firstname'
default='lastname'
12.5.5. Recap
Iterate Keys
Iterate Values
Iterate Items - key-value pairs
By default
dict
iterates over keys
>>> data = {'firstname': 'Alice', 'lastname': 'Apricot'}
Keys
>>> for key in data.keys():
... print(f'{key=}')
key='firstname'
key='lastname'
Values:
>>> for value in data.values():
... print(f'{value=}')
value='Alice'
value='Apricot'
Items (key-value pair):
>>> for item in data.items():
... print(f'{item=}')
item=('firstname', 'Alice')
item=('lastname', 'Apricot')
Default:
>>> for default in data:
... print(f'{default=}')
default='firstname'
default='lastname'
12.5.6. Assignments
# %% About
# - Name: For Dict Keys
# - Difficulty: easy
# - Lines: 3
# - Minutes: 2
# %% 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
# %% English
# 1. Iterate over `DATA` and collect keys in `result: list[str]`
# 2. Use `for` loop and `dict.keys()`
# 3. Run doctests - all must succeed
# %% Polish
# 1. Iteruj po `DATA` i zbierz klucze w `result: list[str]`
# 2. Użyj pętli `for` i `dict.keys()`
# 3. Uruchom doctesty - wszystkie muszą się powieść
# %% Example
# ['username', 'password', 'remember']
# %% Hints
# - `dict.keys()`
# %% Doctests
"""
>>> 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)
['username', 'password', 'remember']
"""
# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -v myfile.py`
# %% Imports
# %% Types
result: list[str]
# %% Data
DATA = {
'username': 'alice',
'password': 'secret',
'remember': True,
}
# %% Result
result = ...
# %% About
# - Name: For Dict Values
# - Difficulty: easy
# - Lines: 3
# - Minutes: 2
# %% 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
# %% English
# 1. Iterate over `DATA` and collect values in `result: list[str]`
# 2. Use `for` loop and `dict.values()`
# 3. Run doctests - all must succeed
# %% Polish
# 1. Iteruj po `DATA` i zbierz wartości w `result: list[str]`
# 2. Użyj pętli `for` i `dict.values()`
# 3. Uruchom doctesty - wszystkie muszą się powieść
# %% Example
# ['alice', 'secret', True]
# %% Hints
# - `dict.values()`
# %% Doctests
"""
>>> 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 len(result) == 3
>>> from pprint import pprint
>>> pprint(result)
['alice', 'secret', True]
"""
# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -v myfile.py`
# %% Imports
# %% Types
result: list[str]
# %% Data
DATA = {
'username': 'alice',
'password': 'secret',
'remember': True,
}
# %% Result
result = ...
# %% About
# - Name: For Dict Items
# - Difficulty: easy
# - Lines: 3
# - Minutes: 2
# %% 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
# %% English
# 1. Iterate over `DATA` and collect key-value pairs in `result: list[str]`
# 2. Use `for` loop and `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 pętli `for` i `dict.items()`
# 3. Nie używaj rozpakowania
# 4. Uruchom doctesty - wszystkie muszą się powieść
# %% Example
# >>> result
# [('username', 'alice'),
# ('password', 'secret'),
# ('remember', True)]
# %% Hints
# - `dict.values()`
# %% Doctests
"""
>>> 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)
[('username', 'alice'),
('password', 'secret'),
('remember', True)]
"""
# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -v myfile.py`
# %% Imports
# %% Types
result: list[tuple[str,str]]
# %% Data
DATA = {
'username': 'alice',
'password': 'secret',
'remember': True,
}
# %% Result
result = ...
# %% About
# - Name: For Dict Unpacking
# - Difficulty: easy
# - Lines: 3
# - Minutes: 2
# %% 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
# %% English
# 1. Iterate over `DATA` and collect key-value pairs in `result: list[str]`
# 2. Use `for` loop and `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 pętli `for` i `dict.items()`
# 3. Użyj rozpakowania
# 4. Uruchom doctesty - wszystkie muszą się powieść
# %% Example
# >>> result
# [('username', 'alice'),
# ('password', 'secret'),
# ('remember', True)]
# %% Hints
# - `dict.values()`
# %% Doctests
"""
>>> 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)
[('username', 'alice'),
('password', 'secret'),
('remember', True)]
"""
# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -v myfile.py`
# %% Imports
# %% Types
result: list[tuple[str,str]]
# %% Data
DATA = {
'username': 'alice',
'password': 'secret',
'remember': True,
}
# %% Result
result = ...
# %% About
# - Name: For Dict Default
# - Difficulty: easy
# - Lines: 3
# - Minutes: 2
# %% 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
# %% English
# 1. Iterate over `DATA` and collect keys in `result: list[str]`
# 2. Use `for` loop
# 3. Do not use `dict.keys()`
# 4. Run doctests - all must succeed
# %% Polish
# 1. Iteruj po `DATA` i zbierz klucze w `result: list[str]`
# 2. Użyj pętli `for`
# 3. Nie używaj `dict.keys()`
# 4. Uruchom doctesty - wszystkie muszą się powieść
# %% Example
# >>> result
# ['username', 'password', 'remember']
# %% Doctests
"""
>>> 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)
['username', 'password', 'remember']
"""
# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -v myfile.py`
# %% Imports
# %% Types
result: list[str]
# %% Data
DATA = {
'username': 'alice',
'password': 'secret',
'remember': True,
}
# %% Result
result = ...
# %% About
# - Name: For Dict Swap
# - Difficulty: easy
# - Lines: 3
# - Minutes: 5
# %% 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
# %% 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ść
# %% Example
# {'virginica': 0,
# 'setosa': 1,
# 'versicolor': 2}
# %% Hints
# - `dict.items()`
# %% Doctests
"""
>>> 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}
"""
# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -v myfile.py`
# %% Imports
# %% Types
result: dict[str,int]
# %% Data
DATA = {
0: 'virginica',
1: 'setosa',
2: 'versicolor',
}
# %% Result
result = ...
# %% About
# - Name: For Dict Endswith
# - Difficulty: medium
# - Lines: 6
# - Minutes: 5
# %% 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
# %% 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ść
# %% Example
# >>> result
# ['alice@example.com',
# 'bob@example.com',
# 'carol@example.com',
# 'dave@example.org',
# 'eve@example.org']
# %% 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 ...`
# %% Doctests
"""
>>> 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)
['alice@example.com',
'bob@example.com',
'carol@example.com',
'dave@example.org',
'eve@example.org']
"""
# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -v myfile.py`
# %% Imports
# %% Types
result: list[str]
# %% Data
DATA = {
'group': 'staff',
'created': '2000-01-02',
'modified': '2000-01-05',
'users': [
{'firstname': 'Alice', 'lastname': 'Apricot', 'email': 'alice@example.com'},
{'firstname': 'Bob', 'lastname': 'Banana', 'email': 'bob@example.com'},
{'firstname': 'Carol', 'lastname': 'Corn', 'email': 'carol@example.com'},
{'firstname': 'Dave', 'lastname': 'Durian', 'email': 'dave@example.org'},
{'firstname': 'Eve', 'lastname': 'Elderberry', 'email': 'eve@example.org'},
{'firstname': 'Mallory', 'lastname': 'Melon', 'email': 'mallory@example.net'},
],
}
DOMAINS = ('example.com', 'example.org')
# %% Result
result = ...