Skip to main content

Section 11.2 Dictionary Operations

The len function and del statement, which we saw in connection with lists, also work with dictionaires. The len function returns the number of key-value pairs in the dictionary. The del statement 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. (We have put one entry per line in the dictionary declaration so that it fits into codelens nicely.)
Dictionaries are also mutable. As we have seen before with lists, this means that 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. Note that the number of key-value pairs is not changed by updating a value.
Similarily, a new shipment of 200 bananas arriving could be handled like this.
After the update, there are now 512 bananas; the dictionary has been modified. We could also have written the update to the number of bananas as inventory['bananas'] += 200; this is one place where compound assignment (as described in Section 2.16) saves us a lot of typing!
If we enter a key that does not yet exist, it will automatically be added to the dictionary:

Checkpoint 11.2.1.

    What is printed by the following statements?
    mydict = {"cat": 12, "dog": 6, "elephant": 23}
    mydict["mouse"] = mydict["cat"] + mydict["dog"]
    print(mydict["mouse"])
    
  • 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.