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': 'Mark', 'lastname': 'Watney'}
>>> data['age'] = 41
>>>
>>> print(data)
{'firstname': 'Mark', 'lastname': 'Watney', 'age': 41}

If key exist:

>>> data = {'firstname': 'Mark', 'lastname': 'Watney', 'age': None}
>>> data['age'] = 41
>>>
>>> print(data)
{'firstname': 'Mark', 'lastname': 'Watney', 'age': 41}

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': 'Mark', 'lastname': 'Watney'}
>>> data.update(age=41)
>>>
>>> print(data)
{'firstname': 'Mark', 'lastname': 'Watney', 'age': 41}

If key exist:

>>> data = {'firstname': 'Mark', 'lastname': 'Watney', 'age': None}
>>> data.update(age=41)
>>>
>>> print(data)
{'firstname': 'Mark', 'lastname': 'Watney', 'age': 41}

7.4.3. Merge Operator

  • Merge (|) adds two dictionaries

  • Since Python 3.9: PEP 584 -- Add Union Operators To dict

>>> a = {'firstname': 'Mark', 'lastname': 'Watney'}
>>> b = {'age': 41}
>>>
>>> data = a | b
>>>
>>> print(data)
{'firstname': 'Mark', 'lastname': 'Watney', 'age': 41}

7.4.4. Increment Merge Operator

  • Update (|=) adds right-hand dictionary to left-hand dictionary

  • Since Python 3.9: PEP 584 -- Add Union Operators To dict

>>> a = {'firstname': 'Mark', 'lastname': 'Watney'}
>>> b = {'age': 41}
>>>
>>> a |= b
>>>
>>> print(a)
{'firstname': 'Mark', 'lastname': 'Watney', 'age': 41}

7.4.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: Mapping Dict Setitem
# - Difficulty: easy
# - Lines: 1
# - Minutes: 2

# %% English
# 1. Use `result: dict`
# 2. Change value for key 'group' to 'admins'
# 3. Use setitem syntax
# 4. Run doctests - all must succeed

# %% Polish
# 1. Użyj `result: dict`
# 2. Zmień wartość dla klucza 'group' na 'admins'
# 3. Użyj składni setitem
# 4. Uruchom doctesty - wszystkie muszą się powieść

# %% Hints
# - `dict[key] = value`

# %% Tests
"""
>>> 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 invalid type, should be dict'

>>> assert all(type(x) is str for x in result.keys()), \
'All dict keys should be str'

>>> assert 'firstname' in result.keys()
>>> assert 'lastname' in result.keys()
>>> assert 'group' in result.keys()

>>> assert 'Mark' in result.values()
>>> assert 'Watney' in result.values()
>>> assert 'users' not in result.values()
>>> assert 'admins' in result.values()

>>> pprint(result, width=40, sort_dicts=False)
{'firstname': 'Mark',
 'lastname': 'Watney',
 'group': 'admins'}
"""

result = {
    'firstname': 'Mark',
    'lastname': 'Watney',
    'group': 'users',
}

# Change value for key 'group' to 'admins'
# Use setitem syntax
# type: dict[str,str]
...


# %% 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: Mapping Dict Update
# - Difficulty: easy
# - Lines: 1
# - Minutes: 2

# %% English
# 1. Use `result: dict`
# 2. Change value for key 'group' to 'admins'
# 3. Use `update` method
# 4. Run doctests - all must succeed

# %% Polish
# 1. Użyj `result: dict`
# 2. Zmień wartość dla klucza 'group' na 'admins'
# 3. Użyj metody `update`
# 4. Uruchom doctesty - wszystkie muszą się powieść

# %% Hints
# - `dict.update(key=value)`

# %% Tests
"""
>>> 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 invalid type, should be dict'

>>> assert all(type(x) is str for x in result.keys()), \
'All dict keys should be str'

>>> assert 'firstname' in result.keys()
>>> assert 'lastname' in result.keys()
>>> assert 'group' in result.keys()

>>> assert 'Mark' in result.values()
>>> assert 'Watney' in result.values()
>>> assert 'users' not in result.values()
>>> assert 'admins' in result.values()

>>> pprint(result, width=40, sort_dicts=False)
{'firstname': 'Mark',
 'lastname': 'Watney',
 'group': 'admins'}
"""

result = {
    'firstname': 'Mark',
    'lastname': 'Watney',
    'group': 'users',
}

# Change value for key 'group' to 'admins'
# Use `update` method
# type: dict[str,str]
...


# %% 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: Mapping Dict UpdateMany
# - Difficulty: easy
# - Lines: 1
# - Minutes: 2

# %% English
# 1. Modify `result: dict`:
#    - change value for key 'firstname' to 'Melissa'
#    - change value for key 'lastname' to 'Lewis'
# 2. Use `update` method
# 3. Run doctests - all must succeed

# %% Polish
# 1. Zmodyfikuj `result: dict`:
#    - zmień wartość dla klucza 'firstname' na 'Melissa'
#    - zmień wartość dla klucza 'lastname' na 'Lewis'
# 2. Użyj metodę `update`
# 3. Uruchom doctesty - wszystkie muszą się powieść

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

# %% Tests
"""
>>> 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 invalid type, should be dict'

>>> assert all(type(x) is str for x in result.keys()), \
'All dict keys should be str'

>>> assert 'firstname' in result.keys()
>>> assert 'lastname' in result.keys()
>>> assert 'group' in result.keys()

>>> assert 'Melissa' in result.values()
>>> assert 'Lewis' in result.values()
>>> assert 'users' in result.values()

>>> pprint(result, width=40, sort_dicts=False)
{'firstname': 'Melissa',
 'lastname': 'Lewis',
 'group': 'users'}
"""

result = {
    'firstname': 'Mark',
    'lastname': 'Watney',
    'group': 'users',
}

# Change value for key 'firstname' to 'Melissa'
# Change value for key 'lastname' to 'Lewis'
# Use `dict.update()` method
# type: dict[str,str]
...


# %% 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: Mapping Dict Union
# - Difficulty: easy
# - Lines: 1
# - Minutes: 2

# %% 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ść

# %% Hints
# - `|` - "or" operator

# %% Tests
"""
>>> 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, \
'Assign your result to variable `result`'
>>> assert type(result) is dict, \
'Variable `result` has invalid type, should be dict'

>>> pprint(result, width=40, sort_dicts=True)
{'botanist': 'Mark Watney',
 'chemist': 'Alex Vogel',
 'commander': 'Melissa Lewis',
 'engineer': 'Beth Johanssen',
 'pilot': 'Rick Martinez',
 'surgeon': 'Chris Beck'}
"""


DATA_A = {
    'commander': 'Melissa Lewis',
    'botanist': 'Mark Watney',
    'pilot': 'Rick Martinez',
}

DATA_B = {
    'chemist': 'Alex Vogel',
    'engineer': 'Beth Johanssen',
    'surgeon': 'Chris Beck',
}

# Define `result: dict` with union of `DATA_A` and `DATA_B`
# type: dict[str, str]
result = ...