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 = {'username': 'alice', 'password': 'secret'}
>>> data['remember'] = 'True'
>>>
>>> print(data)
{'username': 'alice', 'password': 'secret', 'remember': 'True'}

If key exist:

>>> data = {'username': 'alice', 'password': 'secret', 'remember': None}
>>> data['remember'] = 'True'
>>>
>>> print(data)
{'username': 'alice', 'password': 'secret', 'remember': 'True'}

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 = {'username': 'alice', 'password': 'secret'}
>>> data.update(remember='True')
>>>
>>> print(data)
{'username': 'alice', 'password': 'secret', 'remember': 'True'}

If key exist:

>>> data = {'username': 'alice', 'password': 'secret', 'remember': None}
>>> data.update(remember='True')
>>>
>>> print(data)
{'username': 'alice', 'password': 'secret', 'remember': 'True'}

7.4.3. Merge Operator

  • Merge (|) adds two dictionaries

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

>>> a = {'username': 'alice', 'password': 'secret'}
>>> b = {'remember': 'True'}
>>>
>>> data = a | b
>>>
>>> print(data)
{'username': 'alice', 'password': 'secret', 'remember': 'True'}

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 = {'username': 'alice', 'password': 'secret'}
>>> b = {'remember': 'True'}
>>>
>>> a |= b
>>>
>>> print(a)
{'username': 'alice', 'password': 'secret', 'remember': 'True'}

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 '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`

# %% 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 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'}
"""

# %% 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,str]

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

# %% 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 '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)`

# %% 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 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'}
"""

# %% 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,str]

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

# %% 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 'Banana'
# 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 'Banana'
# 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 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 'Alice' not in result.values()
>>> assert 'Apricot' not in result.values()

>>> assert 'Bob' in result.values()
>>> assert 'Banana' in result.values()
>>> assert 'users' in result.values()

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

# %% 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,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, \
'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)
{'alice': 'Alice Apricot',
 'bob': 'Bob Banana',
 '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 -v myfile.py`

# %% Imports

# %% Types
result: dict[str, str]

# %% Data
DATA_A = {
    'alice': 'Alice Apricot',
    'bob': 'Bob Banana',
    'carol': 'Carol Corn',
}

DATA_B = {
    'dave': 'Dave Durian',
    'eve': 'Eve Elderberry',
    'mallory': 'Mallory Melon',
}

# %% Result
result = ...