5.11. Mapping Merge

5.11.1. Update Method

>>> crew = {
...    'commander': 'Melissa Lewis',
...    'botanist': 'Mark Watney',
...    'pilot': 'Rick Martinez'}
>>>
>>> new = {
...    'chemist': 'Alex Vogel',
...    'surgeon': 'Chris Beck',
...    'engineer': 'Beth Johanssen'}
>>>
>>>
>>> crew.update(new)
>>> print(crew)  
{'commander': 'Melissa Lewis',
 'botanist': 'Mark Watney',
 'pilot': 'Rick Martinez',
 'chemist': 'Alex Vogel',
 'surgeon': 'Chris Beck',
 'engineer': 'Beth Johanssen'}

5.11.2. Merge Operator

  • Merge (|) and update (|=) operators have been added to the built-in dict class.

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

>>> crew = {
...    'commander': 'Melissa Lewis',
...    'botanist': 'Mark Watney',
...    'pilot': 'Rick Martinez'}
>>>
>>> new = {
...     'chemist': 'Alex Vogel',
...     'surgeon': 'Chris Beck',
...     'engineer': 'Beth Johanssen'}
>>>
>>>
>>> everyone = crew | new
>>>
>>> print(crew)  
{'commander': 'Melissa Lewis',
 'botanist': 'Mark Watney',
 'pilot': 'Rick Martinez'}
>>>
>>> print(new)  
{'chemist': 'Alex Vogel',
 'surgeon': 'Chris Beck',
 'engineer': 'Beth Johanssen'}
>>>
>>> print(everyone)  
{'commander': 'Melissa Lewis',
 'botanist': 'Mark Watney',
 'pilot': 'Rick Martinez',
 'chemist': 'Alex Vogel',
 'surgeon': 'Chris Beck',
 'engineer': 'Beth Johanssen'}

5.11.3. Increment Merge Operator

>>> crew = {
...    'commander': 'Melissa Lewis',
...    'botanist': 'Mark Watney',
...    'pilot': 'Rick Martinez'}
>>>
>>> new = {
...     'chemist': 'Alex Vogel',
...     'surgeon': 'Chris Beck',
...     'engineer': 'Beth Johanssen'}
>>>
>>>
>>> crew |= new
>>>
>>> print(crew)  
{'commander': 'Melissa Lewis',
 'botanist': 'Mark Watney',
 'pilot': 'Rick Martinez',
 'chemist': 'Alex Vogel',
 'surgeon': 'Chris Beck',
 'engineer': 'Beth Johanssen'}
>>>
>>> print(new)  
{'chemist': 'Alex Vogel',
 'surgeon': 'Chris Beck',
 'engineer': 'Beth Johanssen'}

5.11.4. Assignments