COMP 200 Elements of Computer Science &
COMP 130 Elements of Algorithms and Computation
Spring 2012

Python Dictionaries “Finger Exercises”

A list is essentially a mapping from its indices 0…n-1, which are all integers, to some values. I.e., given an integer i, you can find a corresponding value l[i]. A dictionary is much the same, except that it allows you to map from (almost) any kind of value, not just integers.

Examples

As an example, we could have the following dictionary:

In this example, 4, True, and "silly" are known as the keys, while "hi", 24, and ["very", "very", "very"] are the corresponding values.

Since the keys are not necessarily nicely ordered like the indices of a list, the dictionary itself is not considered to have an order. It may display in a different order than you entered.

What might we use them for? Our motivating example is for word counts. Thus, the keys would be strings, and the values would be integers. Ignoring punctuation and capitalization, the counts for the Beatles' Love Me Do would be

Another text-based example would be a substitution cipher, where we want to map each letter to its coded version.

Creating dictionaries

As seen in the previous examples, we can create a dictionary using curly braces to enclose the key:value pairs, separated by commas. An empty dictionary, with no key:value pairs, just has the curly braces.

We can also create a dictionary by converting a list of pairs:

Operations on dictionaries

As previously illustrated, we can look for the value associated with some key.

We can change a dictionary by changing or creating a key/value pair:

Write a function that takes a list and returns the corresponding dictionary, where the keys are the list indices. I.e., given a list ["cat","dog","shark"], it returns {0: "cat", 1: "dog", 2: "shark"}.

You can remove a key/value pair from a dictionary, too. You'll need that on your assignment.

To see what is in a dictionary, it depends on whether you are looking for the keys or the values.

There are numerous other operations of lesser importance, as described in the Python documentation.

Looping over dictionaries

To access each of the dictionary elements, it is common to loop over the dictionary. This actually loops over the dictionary keys, from which you can get the values. Of course, dictionaries are not ordered, so you don't know which order in which you'll get the keys.

Thus, looping on a dictionary is comparable to looping on a list's range.

However, there is a more “Pythonic” way to loop over both the key and value:

How could you loop over just the values in a similar way? What function did we previously mention to get the values?

Additional optional readings about Python dictionariess