6.8. Mapping SetItem

  • Adds if value not exist

  • Updates if value exist

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

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