6 Storing data in dictionaries

 

This chapter covers

  • Storing values on keys in dictionaries
  • Working with pair objects
  • Using tuples to create dictionaries
  • Comparing dictionaries and arrays
  • Comparing named tuples and dictionaries

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:

  1. 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.
  2. Looking up a value y in dictionary ys with the key "foo".
  3. 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.

6.1 Parsing Roman numerals

While Roman numerals are not very practical to use today, they are useful to learn about for understanding number systems. In particular, when programming, you will encounter various number systems.

6.2 Using the Dict type

6.3 Looping over characters

6.4 Enumerating values and indices

6.5 Explaining the conversion process

6.6 Using dictionaries

6.6.1 Creating dictionaries

6.6.2 Element access