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

We will look at 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 an array where values are looked up exclusively using integer indices. In the next code example the following happens:

  1. Look 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 key in dictionary zs to lookup value z.
x = xs[42]
y = ys["foo"]
z = zs['D']

We will demonstrate the utility of dictionaries by working through a code example involving 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 and 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 in order to understand 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

6.7 Why Use a Dictionary?

6.8 Using named tuples as dictionaries

6.8.1 When do you use a named tuple?

6.8.2 Tying it all together