Key Error

Keys and Dictionaries in Python

Keys in Python are associated with dictionaries. A dictionary is an unordered set of key-value pairs. Keys can technically be made up of any hashable type, but for now let's just consider keys made of strings, numbers, tuples, or any combination thereof.

The following are valid examples of a dictionary with each type of key. In this first example, Anna is the key represented as a str (string), and 1481.10 is the float value associated with that key.

stringKeyDictionary = { 'Anna' : 1481.10 }
Fig. 1: A dictionary containing a str based key

Here, the number 25 is the key represented as an integer, and the string 'twenty-five' is its associated value:

numberKeyDictionary = { 25 : 'twenty-five' }
Fig. 2: A dictionary containing a numeric key

Finally, this is a dictionary where the key is a tuple, and the value is a list of things associated with said tuple:

tupleKeyDictionary = { ('fruits', 'vegetables') : ['apples','pears','sprouts'] }
Fig. 3: A dictionary containing a tuple based key

Note that though the above dictionaries only have keys of one specific type, this needn't be the case. As long as your keys are of the allowed types specified above, you can mix and match dictionary key types in any which way you like.

KeyErrors in Python

KeyErrors in Python are raised if you attempt to access an invalid key in a dictionary. More often than not, this means that the key you were trying to look up simply isn't there. As an example, consider the following (incomplete) dictionary of orchestral instruments:

>>> instDictionary = {'Winds': ['Clarinet', 'Flute', 'Oboe']}
>>> instDictionary['Brass'] = ['Trombone', 'Trumpet', 'Tuba']
>>> instDictionary['Strings'] = ['Violin', 'Cello', 'Bass']

After executing these three lines, the dictionary will contain three key-value pairs. Now let's say we try and access the value associated with a string key 'Percussion'. Since this key doesn't exist in our dictionary yet, Python will throw a KeyError:

>>> print instDictionary['Percussion']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'Percussion'

In PyLearn, the same KeyError message would look something like this:

>>> print instDictionary['Percussion']
KeyError: 'Percussion' is not a key in the dictionary.

Avoiding KeyErrors in Python

In Python, the best way to avoid encountering a KeyError is to verify that the key you want to access actually exists before attempting to do so. Thankfully, Python provides us with a couple of nifty ways to do just that.

All Python dictionary objects have an associated method has_key() which returns a boolean indicating whether or not the provided key exists in the dictionary. So, returning to our prior instrument dictionary example, we get the following result:

>>> print instDictionary.has_key('Percussion')
False

Great! But how do we put this into use? We could write an if statement, using the result of this method to determine whether or not we should try to access the given key. And that would work just fine:

>>> if instDictionary.has_key('Percussion'):
       print instDictionary['Percussion']

However, because Python is a friendly language, it also provides an alternate, cleaner syntax for this specific use-case, using the in keyword:

>>> if 'Percussion' in instDictionary:
       print instDictionary['Percussion']