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
# >>> result
# ['firstname', 'lastname', 'age']
# %% Hints
# - `dict.keys()`
# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'
>>> assert result is not Ellipsis, \
'Variable `result` has an invalid value; assign result of your program to it.'
>>> assert type(result) is list, \
'Variable `result` has an invalid type; expected: `list`.'
>>> assert all(type(x) is str for x in result)
>>> assert len(result) == 3
>>> from pprint import pprint
>>> pprint(result)
['firstname', 'lastname', 'age']
"""
# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -f -v myfile.py`
# %% Imports
# %% Types
result: list[str]
# %% Data
DATA = {
'firstname': 'Alice',
'lastname': 'Apricot',
'age': 20,
}
# %% 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
# >>> result
# ['Alice', 'Apricot', 20]
# %% Hints
# - `dict.values()`
# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'
>>> assert result is not Ellipsis, \
'Variable `result` has an invalid value; assign result of your program to it.'
>>> assert type(result) is list, \
'Variable `result` has an invalid type; expected: `list`.'
>>> assert len(result) == 3
>>> from pprint import pprint
>>> pprint(result)
['Alice', 'Apricot', 20]
"""
# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -f -v myfile.py`
# %% Imports
# %% Types
result: list[str]
# %% Data
DATA = {
'firstname': 'Alice',
'lastname': 'Apricot',
'age': 20,
}
# %% 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
# [('firstname', 'Alice'),
# ('lastname', 'Apricot'),
# ('age', 20)]
# %% Hints
# - `dict.values()`
# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'
>>> assert result is not Ellipsis, \
'Variable `result` has an invalid value; assign result of your program to it.'
>>> assert type(result) is list, \
'Variable `result` has an invalid type; expected: `list`.'
>>> assert all(type(x) is tuple for x in result)
>>> assert len(result) == 3
>>> from pprint import pprint
>>> pprint(result, width=30)
[('firstname', 'Alice'),
('lastname', 'Apricot'),
('age', 20)]
"""
# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -f -v myfile.py`
# %% Imports
# %% Types
result: list[tuple[str,str]]
# %% Data
DATA = {
'firstname': 'Alice',
'lastname': 'Apricot',
'age': 20,
}
# %% 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
# [('firstname', 'Alice'),
# ('lastname', 'Apricot'),
# ('age', 20)]
# %% Hints
# - `dict.values()`
# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'
>>> assert result is not Ellipsis, \
'Variable `result` has an invalid value; assign result of your program to it.'
>>> assert type(result) is list, \
'Variable `result` has an invalid type; expected: `list`.'
>>> assert all(type(x) is tuple for x in result)
>>> assert len(result) == 3
>>> from pprint import pprint
>>> pprint(result, width=30)
[('firstname', 'Alice'),
('lastname', 'Apricot'),
('age', 20)]
"""
# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -f -v myfile.py`
# %% Imports
# %% Types
result: list[tuple[str,str]]
# %% Data
DATA = {
'firstname': 'Alice',
'lastname': 'Apricot',
'age': 20,
}
# %% 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
# ['firstname', 'lastname', 'age']
# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'
>>> assert result is not Ellipsis, \
'Variable `result` has an invalid value; assign result of your program to it.'
>>> assert type(result) is list, \
'Variable `result` has an invalid type; expected: `list`.'
>>> assert all(type(x) is str for x in result)
>>> assert len(result) == 3
>>> from pprint import pprint
>>> pprint(result)
['firstname', 'lastname', 'age']
"""
# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -f -v myfile.py`
# %% Imports
# %% Types
result: list[str]
# %% Data
DATA = {
'firstname': 'Alice',
'lastname': 'Apricot',
'age': 20,
}
# %% 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
# >>> result
# {'users': 0,
# 'staff': 1,
# 'admins': 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, \
'Variable `result` has an invalid value; assign result of your program to it.'
>>> assert type(result) is dict, \
'Variable `result` has an invalid type; expected: `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 'users' in result.keys()
>>> assert 'staff' in result.keys()
>>> assert 'admins' 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)
{'users': 0,
'staff': 1,
'admins': 2}
"""
# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -f -v myfile.py`
# %% Imports
# %% Types
result: dict[str,int]
# %% Data
DATA = {
0: 'users',
1: 'staff',
2: 'admins',
}
# %% 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, \
'Variable `result` has an invalid value; assign result of your program to it.'
>>> assert type(result) is list, \
'Variable `result` has an invalid type; expected: `list`.'
>>> assert len(result) > 0, \
'Variable `result` length is zero; it should contain items.'
>>> assert all(type(x) is str for x in result), \
'Variable `result` has elements of an invalid type; all items should be: `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 -f -v myfile.py`
# %% Imports
# %% Types
result: list[str]
# %% Data
DATA = {
'database': 'myapp',
'table': 'users',
'rows': [
{'username': 'alice', 'email': 'alice@example.com'},
{'username': 'bob', 'email': 'bob@example.com'},
{'username': 'carol', 'email': 'carol@example.com'},
{'username': 'dave', 'email': 'dave@example.org'},
{'username': 'eve', 'email': 'eve@example.org'},
{'username': 'mallory', 'email': 'mallory@example.net'},
]
}
DOMAINS = ('example.com', 'example.org')
# %% Result
result = ...