Working with Dictionaries
Dictionaries are mutable, so we can change the value assigned to a key, add new key/value pairs, or remove key/value pairs.
Since dictionaries are unordered, we have no options for sorting or rearranging the key/value pairs within the collections.
Change One Value
To update a single value in a dictionary, use the syntax:
dictionary_name[key] = new_valuedictionary_name[key] identifies the value in the collection that we want to
change. The = operator assigns new_value to that key.
Example
| |
Console Output
{'Mom' : '555-5555', 'Work' : '555-5556', 'Home' : '123-456-7890'}
{'Mom' : '555-5555', 'Work' : '314-555-5556', 'Home' : '123-456-7890'}
Note
We cannot use this method to change the names of the keys.
Add a New Key/Value Pair
After defining a dictionary, we can add new new key/value pairs at any time by using bracket syntax:
dictionary_name['new_key'] = new_valueExample
| |
Console Output
{'Mom' : '555-5555', 'Work' : '555-5556', 'Home' : '123-456-7890'}
{'Mom' : '555-5555', 'Work' : '555-5556', 'Home' : '123-456-7890', 'BFF' : '555-5557'}
Remove a Key/Value Pair
To remove a key/value pair from a dictionary, use the del keyword. The
general syntax is:
del dictionary_name[key]Example
| |
Console Output
{'Mom' : '555-5555', 'Work' : '555-5556', 'Home' : '123-456-7890', 'BFF' : '555-5557'}
{'Mom' : '555-5555', 'Work' : '555-5556', 'BFF' : '555-5557'}
Note
Once we define a key, it remains in the dictionary unless we use del to
remove it.
For example, if we wanted to rename the key 'Mom' to 'Mother', we
would have to delete the old key first, then add a new key/value pair.
del phone_book['Mom']
phone_book['Mother'] = '555-5555'Check Your Understanding
Question
Given the following dictionary:
pet_population = {'cats' : 10, 'dogs' : 5, 'elephants' : 25}What value does len(pet_population) return?
- 3
- 6
- 40
Question
Using the same pet_population dictionary, what would the following
statement do?
pet_population['birds'] = 5- Throw an error message because
pet_populationdoes not contain a'birds'key. - Add the
'birds' : 5key/value pair to the dictionary. - Add five
'birds'keys to the dictionary. - Replace the
'dogs'key with'birds'.