Hour 9. Dictionaries and Sets
What You’ll Learn in This Hour:
What a dictionary is
How to populate a dictionary
How to obtain information from a dictionary
What a set is
How to program with sets
In this hour, you will read about two additional Python collection types: dictionaries and sets. You
will learn what they are, how to create them, how to fill them with data, how to manage them, and
how to use them in Python scripts.
Understanding Python Dictionary Terms
A dictionary is a simple structure, also called an associative array, that contains data. Each piece of
data contained in a dictionary is called an element, an entry, or a record. Each element is broken up
into two parts. One part is called the value. To locate a particular value in a dictionary, you use the
other part of the dictionary element, the key. A key is immutable, and it is assigned only to one
particular value in the dictionary. Thus, another name for a dictionary element is a key/value pair.
By the Way: When Is a Dictionary Not a Dictionary?
Don’t let the term dictionary fool you. A dictionary in Python is not the same as a
reference book containing word definitions found in the library. For one thing, a word
in a dictionary reference may have multiple definitions. A key in a Python dictionary
has only one value.
An example of a Python dictionary is a college, which has a list of student names and their associated
student ID numbers. The college decides to build an array, where the student ID number would be the
key and the student name would be the value. Each student ID would be assigned to only one student
name. Thus, the key/value pair for this college dictionary would be the student ID number/student
name.
Exploring Dictionary Basics
Before you can start programming with dictionaries, you need to learn a few basics, such as how to
access the data in a dictionary. Learning these basics will help when you read through the
“Programming with Dictionaries” section of this hour.
Creating a Dictionary
Creating and using dictionaries in Python is very simple. To create an empty dictionary, you just use
the Python statement dictionary_name = {}.