Modifying Values in a Dictionary:

  • To modify a value in a dictionary, give the name of the dictionary with the key in square brackets and then the new value you want associated with that key.
python
1person = {
2'firstName': 'michael',
3'lastName': 'burnham',
4}
5
6person['lastName'] = 'martin-green'
7print(person)

Output:

1{'firstName': 'michael', 'lastName': 'martin-green'}
  • We first define a dictionary for person that contains only the first and last name.
  • Then we change the value associated with the key, in this case, ‘burnham’ to ‘martin-green’.

Removing Key-Value Pairs:

  • The del statement can be used to completely remove a key-value pair.
python
1person = {
2'firstName': 'michael',
3'lastName': 'burnham',
4}
5print(person)
6
7del person['lastName']
8print(person)

Output:

1{'firstName': 'michael', 'lastName': 'burnham'}
2{'firstName': 'michael'}
  • Here we tell Python to delete the key ‘lastName’ from the person dictionary and to remove the value associated with that key as well. Note that the rest of the dictionary is unaffected.