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:
- Look up the 42nd value
x
in arrayxs
. Values in arrays are ordered. Howeverxs
could have been a dictionary as well, since dictionary keys can be anything including integers.
- Looking up a value
y
in dictionaryys
with the key"foo"
.
- Using a character
'D'
rather than a string as key in dictionaryzs
to lookup valuez
.
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.
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.