2. Dictionary Operations¶
Dictionaries are mutable. Therefore, like lists, their contents can be changed. One way to do that is with the del
statement which removes a key-value pair from a dictionary. For example, the following dictionary contains the names of various fruits and the number of each fruit in stock. If someone buys all of the pears, we can remove the entry from the dictionary.
And — as we’ve seen with lists — since it is mutable, the dictionary can be modified by referencing an association on the left hand side of the assignment statement. In the previous example, instead of deleting the entry for pears
, we could have set the inventory to 0
.
Similarily, a new shipment of 200 bananas arriving could be handled like this.
Notice that there are now 512 bananas—the dictionary has been modified. Note also that the len
function also works on dictionaries. It returns the number of key-value pairs:
Check your understanding
- 12
- 12 is associated with the key cat.
- 0
- The key mouse will be associated with the sum of the two values.
- 18
- Yes, add the value for cat and the value for dog (12 + 6) and create a new entry for mouse.
- Error, there is no entry with mouse as the key.
- Since the new key is introduced on the left hand side of the assignment statement, a new key-value pair is added to the dictionary.
What is printed by the following statements?
my_dict = {"cat":12, "dog":6, "elephant":23}
my_dict["mouse"] = my_dict["cat"] + my_dict["dog"]
print(my_dict["mouse"])