Python Dictionaries

Today's lecture introduces a powerful data type that is available to you in Python called the Dictionary. This expands on some of the ability you have with Lists, but in a more general way. With a List, you access its elements through integer indices like: names[3] = 'William'. Those indices are just mappings from a number to a value. Now in a List it makes sense because you have an ordered list of items, and the index is just its position. A Dictionary doesn't have a fixed order, but instead lets you map strings to values. For instance, perhaps you want to map a title to a name like so: names['principal'] = 'William'. That's a dictionary! Today we'll talk about how to do this, and show how this opens up doors for you to different approaches of storing information.

Read the book! That's the point of the textbook: it gives you all the details you need.

Reading: Chapter 9

Please read Chapter 9 on Dictionaries.

Today in Class

We will discuss and learn about:

You should be able to understand these programs.

Try this out yourself. This program opens a text file (download here) that has names and grades. Each line is a name followed by one grade. It then lets the user query for grades by name:

# Load the file and put it in a dictionary
grades = dict()
fh = open('grades.txt')
for line in fh:
    name, grade = line.split()   # the line "William 80" splits into two parts
    grades[name] = int(grade)

# This prints:  {'William': 80, 'Sara': 76, 'Jack': 94, 'Reid': 84, 'Grace': 82, 'Wendy': 93}
print(grades)

# User queries for grades over and over.
while True:
    name = input("Name? ")
    # Test that the name is a key in the Dictionary
    if name in grades.keys():
        print("Grade is", grades[name])
    else:
        print("Not found.")