Jason M. Grant

Assistant Professor of Computer Science


Introduction is taken from Think Python, though the examples have been somewhat modified.

What is a Dictionary?

dictionaryis like a list, but more general. In a list, the indices have to be integers; in a dictionary they can be (almost) any type.

A dictionary contains a collection of indices, which are called keys, and a collection of values. Each key is associated with a single value. The association of a key and a value is called a key-value pair or sometimes an item.

In mathematical language, a dictionary represents a mappingfrom keys to values, so you can also say that each key “maps to” a value. As an example, we’ll build a dictionary that maps from English to Spanish words, so the keys and the values are all strings.

The function dictcreates a new dictionary with no items. Because dictis the name of a built-in function, you should avoid using it as a variable name.

>>> satdict = dict()
>>> satdict

The curly-brackets, {}, represent an empty dictionary. To add items to the dictionary, you can use square brackets:

>>> satdict['abate'] = 'become less in amount or intensity'

This line creates an item that maps from the key 'abate'to the value 'become less in amount or intensity'. If we print the dictionary again, we see a key-value pair with a colon between the key and value:

>>> satdict
{'abate': 'become less in amount or intensity'}

This output format is also an input format. For example, you can create a new dictionary with three items:

>>> eng2sp = {'one': 'uno', 'two': 'dos', 'three': 'tres'}

In the following code, we demonstrate how to create a dictionary and iterate through the dictionary.

What if we know the value or part of the value of a word in the dictionary. Can we find it’s corresponding key? Absolutely. We call this a reverse search.