Quarry School

Look up a key — quick review

In plain words

A phone book is not read by position: you look up a name and read the number beside it.

Rule

A dictionary holds key: value pairs with unique keys. d[k] gives the value stored with key k, and a missing key raises a KeyError. d[k] = v adds the pair, or replaces the value when k is already a key. k in d is True when k is a key.

Step

  1. Write each key with its value, in pairs, as the dictionary is built.

  2. For d[k] = v, replace the value if k is already a key; otherwise add the new pair at the end, since the keys keep the order they were added in.

  3. For d[k], find the key and read its value; if the key is missing, the program stops with a KeyError.

  4. For k in d, answer True when k is one of the keys, and False otherwise.

Trap

Reading a key that was never stored stops the program with a KeyError. When a key may be missing, test it with in first.

A dictionary is not read by position. phone[0] looks for the key 0, not the first pair, and here it stops with a KeyError because 0 is not one of its keys.