Section B.2 Dictionaries
Subsection B.2.1 Colors of Fruits
In Python and SageMath, a dictionary is a convenient data structure for establishing a relationship between sets of data. From the point of view of this text, we can think of a dictionary as a concrete realization of a relation between two sets or on a single set. A dictionary resembles a function in that there is a set of data values called the
keys
, and for each key, there is a value
. The value associated with a key can be almost anything, but it is most commonly a list.To illustrate the use of dictionaries, we will define a relationship between colors and fruits. The keys will be a set of colors and values associated with each color will be a list of fruits that can take on that color. We will demonstrate how to initialize the dictionary and how to add to it. The following series of assignments have no output, so we add a print statement to verify that this cell is completely evaluated.
We distinguish a color from a fruit by capitalizing colors but not fruit. The keys of this dictionary are the colors. The
keys()
method returns an interator; so to get a list of keys we wrap the result with list()
.As an afterthought, we might add the information that a raspberry is red as follows. You have to be careful in that if ’Red’ isn’t already in the dictionary, it doesn’t have a value. This is why we need an if statement.
A dictionary is iterable, with an iterator taking on values that are the keys. Here we iterate over our dictionary to output lists consisting of a color followed by a list of fruits that come in that color.
We can view a graph of this relation between colors and fruits, but the default view is a bit unconventional.
With a some additional coding we can line up the colors and fruits in their own column. First we set the positions of colors on the left with all \(x\)-coordinates equal to -5 using another dictionary called
vertex_pos
.Next, we place the fruit vertices in another column with \(x\)-coordinates all equal to 5. In order to do this, we first collect all the fruit values into one set we call
fruits
.Now the graph looks like a conventional graph for a relation between two different sets. Notice that it’s not a function.
You have attempted of activities on this page.