7.4. Mapping Setitem
Adds if value not exist
Updates if value exist
7.4.1. Setitem
if key is missing: adds key-value pair
if key exist: overwrites value
setitem -
data[key] = value
If key is missing:
>>> data = {
... 'firstname': 'Alice',
... 'lastname': 'Apricot',
... }
>>>
>>> data['age'] = 20
>>>
>>> print(data)
{'firstname': 'Alice', 'lastname': 'Apricot', 'age': 20}
If key already exists:
>>> data = {
... 'firstname': 'Alice',
... 'lastname': 'Apricot',
... 'age': 20,
... }
>>>
>>> data['age'] = 99
>>>
>>> print(data)
{'firstname': 'Alice', 'lastname': 'Apricot', 'age': 99}
7.4.2. Update Method
if key is missing: adds key-value pair
if key exist: overwrites value
Can update multiple values at once
If key is missing:
>>> data = {
... 'firstname': 'Alice',
... 'lastname': 'Apricot',
... }
>>>
>>> data.update(age=20)
>>>
>>> print(data)
{'firstname': 'Alice', 'lastname': 'Apricot', 'age': 20}
If key already exist:
>>> data = {
... 'firstname': 'Alice',
... 'lastname': 'Apricot',
... 'age': 20,
... }
>>>
>>> data.update(age=99)
>>>
>>> print(data)
{'firstname': 'Alice', 'lastname': 'Apricot', 'age': 99}
You can update multiple values at once:
>>> data = {
... 'firstname': 'Alice',
... 'lastname': 'Apricot',
... 'age': 20,
... }
>>>
>>> data.update(age=99, group='users')
>>>
>>> print(data)
{'firstname': 'Alice', 'lastname': 'Apricot', 'age': 99, 'group': 'users'}
You can also use another dictionary to update values:
>>> data = {
... 'firstname': 'Alice',
... 'lastname': 'Apricot',
... 'age': 20,
... }
>>>
>>> data.update({'age': 99, 'group': 'users'})
>>>
>>> print(data)
{'firstname': 'Alice', 'lastname': 'Apricot', 'age': 99, 'group': 'users'}
7.4.3. Merge Operator
Merge (
|
) adds two dictionariesSince Python 3.9: PEP 584 -- Add Union Operators To dict
>>> user = {
... 'firstname': 'Alice',
... 'lastname': 'Apricot',
... }
>>>
>>> permissions = {
... 'is_active': True,
... 'is_staff': True,
... 'is_admin': False,
... }
>>>
>>> result = user | permissions
>>>
>>> print(result)
{'firstname': 'Alice', 'lastname': 'Apricot', 'is_active': True, 'is_staff': True, 'is_admin': False}
7.4.4. Increment Merge Operator
Update (
|=
) adds right-hand dictionary to left-hand dictionarySince Python 3.9: PEP 584 -- Add Union Operators To dict
>>> user = {
... 'firstname': 'Alice',
... 'lastname': 'Apricot',
... }
>>>
>>> permissions = {
... 'is_active': True,
... 'is_staff': True,
... 'is_admin': False,
... }
>>>
>>> user |= permissions
>>>
>>> print(user)
{'firstname': 'Alice', 'lastname': 'Apricot', 'is_active': True, 'is_staff': True, 'is_admin': False}
7.4.5. Recap
Adds if value not exist
Updates if value exist
Setitem:
dict[key] = value
Update method:
dict.update(key=value)
Merge operator:
a | b
,a |= b
7.4.6. Assignments
# %% About
# - Name: Mapping Dict Setitem
# - Difficulty: easy
# - Lines: 1
# - 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. Use `result: dict`
# 2. Change value for key 'age' to 20
# 3. Use setitem syntax
# 4. Run doctests - all must succeed
# %% Polish
# 1. Użyj `result: dict`
# 2. Zmień wartość dla klucza 'age' na 20
# 3. Użyj składni setitem
# 4. Uruchom doctesty - wszystkie muszą się powieść
# %% Example
# >>> result
# {'firstname': 'Alice',
# 'lastname': 'Apricot',
# 'age': 20}
# %% Hints
# - `dict[key] = value`
# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'
>>> from pprint import pprint
>>> assert type(result) is dict, \
'Variable `result` has an invalid type; expected: `dict`.'
>>> assert all(type(x) is str for x in result.keys()), \
'Variable `result.keys()` has elements of an invalid type; all items should be: `str`.'
>>> assert 'firstname' in result.keys()
>>> assert 'lastname' in result.keys()
>>> assert 'age' in result.keys()
>>> assert 'Alice' in result.values()
>>> assert 'Apricot' in result.values()
>>> assert None not in result.values()
>>> assert 20 in result.values()
>>> pprint(result, width=40, sort_dicts=False)
{'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: dict[str,str|int]
# %% Data
result = {
'firstname': 'Alice',
'lastname': 'Apricot',
'age': None,
}
# %% Result
# %% About
# - Name: Mapping Dict Update
# - Difficulty: easy
# - Lines: 1
# - 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. Use `result: dict`
# 2. Change value for key 'age' to 99
# 3. Use `update` method
# 4. Run doctests - all must succeed
# %% Polish
# 1. Użyj `result: dict`
# 2. Zmień wartość dla klucza 'age' na 99
# 3. Użyj metody `update`
# 4. Uruchom doctesty - wszystkie muszą się powieść
# %% Example
# >>> result
# {'firstname': 'Alice',
# 'lastname': 'Apricot',
# 'age': 20}
# %% Hints
# - `dict.update(key=value)`
# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'
>>> from pprint import pprint
>>> assert type(result) is dict, \
'Variable `result` has an invalid type; expected: `dict`.'
>>> assert all(type(x) is str for x in result.keys()), \
'Variable `result.keys()` has elements of an invalid type; all items should be: `str`.'
>>> assert 'firstname' in result.keys()
>>> assert 'lastname' in result.keys()
>>> assert 'age' in result.keys()
>>> assert 'Alice' in result.values()
>>> assert 'Apricot' in result.values()
>>> assert None not in result.values()
>>> assert 20 in result.values()
>>> pprint(result, width=40, sort_dicts=False)
{'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: dict[str,str|int]
# %% Data
result = {
'firstname': 'Alice',
'lastname': 'Apricot',
'age': None,
}
# %% Result
# %% About
# - Name: Mapping Dict UpdateMany
# - Difficulty: easy
# - Lines: 1
# - 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. Modify `result: dict`:
# - change value for key 'firstname' to 'Bob'
# - change value for key 'lastname' to 'Blackthorn'
# 2. Use `update` method
# 3. Run doctests - all must succeed
# %% Polish
# 1. Zmodyfikuj `result: dict`:
# - zmień wartość dla klucza 'firstname' na 'Bob'
# - zmień wartość dla klucza 'lastname' na 'Blackthorn'
# 2. Użyj metodę `update`
# 3. Uruchom doctesty - wszystkie muszą się powieść
# %% Hints
# - `dict.update()`
# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'
>>> from pprint import pprint
>>> assert type(result) is dict, \
'Variable `result` has an invalid type; expected: `dict`.'
>>> assert all(type(x) is str for x in result.keys()), \
'Variable `result.keys()` has elements of an invalid type; all items should be: `str`.'
>>> assert 'firstname' in result.keys()
>>> assert 'lastname' in result.keys()
>>> assert 'group' in result.keys()
>>> assert 'Alice' not in result.values()
>>> assert 'Apricot' not in result.values()
>>> assert 'Bob' in result.values()
>>> assert 'Blackthorn' in result.values()
>>> assert 'users' in result.values()
>>> pprint(result, width=40, sort_dicts=False)
{'firstname': 'Bob',
'lastname': 'Blackthorn',
'group': 'users'}
"""
# %% 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,str]
# %% Data
result = {
'firstname': 'Alice',
'lastname': 'Apricot',
'group': 'users',
}
# %% Result
# %% About
# - Name: Mapping Dict Union
# - Difficulty: easy
# - Lines: 1
# - 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. Use `DATA_A: dict`
# 2. Use `DATA_B: dict`
# 3. Define `result: dict` with union of `DATA_A` and `DATA_B`
# 4. Run doctests - all must succeed
# %% Polish
# 1. Użyj `DATA_A: dict`
# 2. Użyj `DATA_B: dict`
# 3. Zdefiniuj `result: dict` z unią `DATA_A` i `DATA_B`
# 4. Uruchom doctesty - wszystkie muszą się powieść
# %% Exp
# %% Hints
# - `|` - "or" operator
# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'
>>> from pprint import pprint
>>> import string
>>> 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`.'
>>> pprint(result, width=40, sort_dicts=True)
{'alice': 'Alice Apricot',
'bob': 'Bob Blackthorn',
'carol': 'Carol Corn',
'dave': 'Dave Durian',
'eve': 'Eve Elderberry',
'mallory': 'Mallory Melon'}
"""
# %% 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, str]
# %% Data
DATA_A = {
'alice': 'Alice Apricot',
'bob': 'Bob Blackthorn',
'carol': 'Carol Corn',
}
DATA_B = {
'dave': 'Dave Durian',
'eve': 'Eve Elderberry',
'mallory': 'Mallory Melon',
}
# %% Result
result = ...