This chapter introduces a new data type called a dictionary. In some other languages this datatype is also referred to as a map. In dictionaries, values are looked up by keys, as opposed to being looked up exclusively using integer indices, like in an array. The code example illustrates the difference. Each line performs the following operations:
- Looking up the 42nd value x in array xs. Values in arrays are ordered. However, xs could have been a dictionary as well, since dictionary keys can be anything, including integers.
- Looking up a value y in dictionary ys with the key "foo".
- Using a character 'D' rather than a string as the key in the dictionary zs to lookup value z.
x = xs[42] y = ys["foo"] z = zs['D']
You will discover the utility of dictionaries by working through a code example involving the conversion of Roman numerals to decimal values and back. A dictionary will be used to keep track of what value a letter such as I, V, or X corresponds to in the decimal system.