CSci 150: Foundations of computer science
Home Syllabus Readings Projects Tests

Dictionaries

A dictionary holds a number of values, each associated with a different key. One simple application of a dictionary is a phone book (or contact list), where the key might be a person's name, which you can use to look up that person's phone number.

Creating a dictionary is simple: Just use an empty set of braces.

pres = {}

We can put a value into dictionary using brackets, just like with lists. With lists, though, the index in the brackets must be an integer between 0 and the list's length; but with a dictionary, the value in brackets can be anything. (Well, mostly anything.)

pres['Reagan'] = 1980
pres['Bush'] = 1988
pres['Clinton'] = 1992
pres['Bush'] = 2000

The first line here says to associate 1980 with the word Reagan; the second line says to associate 1988 with Bush; the third line says to associate 1992 with Clinton; and the fourth says to associate 2000 with Bush.

Note that only one value can be associated with each key. So when we associate a new value with Bush, the dictionary simply forgets the old value altogether. If we try to access the value associated with Bush, then, we would get 2000.

print(pres['Bush'])                          # displays 2000

You can think of pres as a table, with the following values.

Bush2000
Clinton1992
Reagan1980

A dictionary is a one-way mapping. If we have a key, we can easily find the value associated with it; but if we have a value, we cannot find which key(s) have that value.

print(pres[1992])                            # crash with "KeyError"

The in operator allows us to ask whether the dictionary contains a particular key. For example, we can have an if statement like “if 'Bush' in pres:”, and we would enter the if when the word Bush is a key for the dictionary.

for name in ['Reagan''Obama']:             # displays "Reagan: 1980"
  if name in pres:                           #     then "Obama?"
    print(name + ': ' + str(pres[name]))
  else:
    print(name + '?')

Another sometimes-useful operation for dictionaries is the keys method, which returns a sequence containing all the keys currently in the dictionary. This sequence is an unpredictable order; if we want the keys in order, we would want to use the sorted function.

names = pres.keys()
names_sort = sorted(names)
print(names_sort)        # displays ['Bush', 'Clinton', 'Reagan']

Putting all these together, here is a simple program that reads a line from the user and then displays how many times each character appears in that word.

word = input()
counts = {}
for letter in word:
    if letter in counts:
        counts[letter] += 1
    else:
        counts[letter] = 1

for letter in sorted(counts.keys()):
    print('{0} {1:2d}'.format(lettercounts[letter]))

For example, if the user executes this program and enters bookkeeper, the output would be:

b  1
e  3
k  2
o  2
p  1
r  1

In both these examples, we worked with dictionaries where all the keys happened to be strings, whereas all the values happened to be integers. However, dictionaries can work with different types. For instance, we could easily create a dictionary mapping integer keys to other integers.

next_fib = {}
next_fib[1] = 2
next_fib[2] = 3
next_fib[3] = 5
next_fib[5] = 8
next_fib[8] = 13