7.4. Mapping SetItem

  • Adds if value not exist

  • Updates if value exist

7.4.1. Set Item Method

>>> crew = {
...     'commander': 'Melissa Lewis',
...     'botanist': 'Mark Watney',
...     'pilot': 'Rick Martinez',
... }
>>>
>>>
>>> crew['chemist'] = 'Alex Vogel'
>>> print(crew)  
{'commander': 'Melissa Lewis',
 'botanist': 'Mark Watney',
 'pilot': 'Rick Martinez',
 'chemist': 'Alex Vogel'}
>>> crew = {
...     'commander': 'Melissa Lewis',
...     'botanist': 'Mark Watney',
...     'pilot': 'Rick Martinez',
... }
>>>
>>>
>>> crew['commander'] = 'Alex Vogel'
>>> print(crew)  
{'commander': 'Alex Vogel',
 'botanist': 'Mark Watney',
 'pilot': 'Rick Martinez'}

7.4.2. Update Method

>>> crew = {
...     'commander': 'Melissa Lewis',
...     'botanist': 'Mark Watney',
...     'pilot': 'Rick Martinez',
... }
>>>
>>>
>>> crew.update(chemist='Alex Vogel')
>>> print(crew)  
{'commander': 'Melissa Lewis',
 'botanist': 'Mark Watney',
 'pilot': 'Rick Martinez',
 'chemist': 'Alex Vogel'}
>>> crew = {
...     'commander': 'Melissa Lewis',
...     'botanist': 'Mark Watney',
...     'pilot': 'Rick Martinez',
... }
>>>
>>>
>>> crew.update(commander='Alex Vogel')
>>> print(crew)  
{'commander': 'Alex Vogel',
 'botanist': 'Mark Watney',
 'pilot': 'Rick Martinez'}

7.4.3. 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'}

7.4.4. 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'}