Look up a key — quick review
A phone book is not read by position: you look up a name and read the number beside it.
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.
Write each key with its value, in pairs, as the dictionary is built.
For
d[k] = v, replace the value ifkis already a key; otherwise add the new pair at the end, since the keys keep the order they were added in.For
d[k], find the key and read its value; if the key is missing, the program stops with a KeyError.For
k in d, answerTruewhenkis one of the keys, andFalseotherwise.
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.