Non-Programmer's Tutorial for Python 2.6/Dictionaries

This chapter is about dictionaries. If you open a dictionary, you should notice every entry consists of two parts, a word and the word's definition. The word is the key to finding out what a word means, and what the word means is considered the value for that key. In Python, dictionaries have keys and values. Keys are used to find values. Here is an example of a dictionary in use:

def print_menu():
    print '1. Print Dictionary'
    print '2. Add definition'
    print '3. Remove word'
    print '4. Lookup word'
    print '5. Quit'
    print

words = {}
menu_choice = 0
print_menu()

while menu_choice != 5:
    menu_choice = input("Type in a number (1-5): ")
    if menu_choice == 1:
        print "Definitions:"
        for x in words.keys():
            print x, ": ", words[x]
        print
    elif menu_choice == 2:
        print "Add definition"
        name = raw_input("Word: ")
        means = raw_input("Definition: ")
        words[name] = means
    elif menu_choice == 3:
        print "Remove word"
        name = raw_input("Word: ")
        if name in words:
            del words[name]
            print name, " was removed."
        else:
            print name, " was not found."
    elif menu_choice == 4:
        print "Lookup Word"
        name = raw_input("Word: ")
        if name in words:
            print "The definition of ", name, " is: ", words[name]
        else:
            print "No definition for ", name, " was found."
    elif menu_choice != 5:
        print_menu()

And here is my output:

1. Print Dictionary
2. Add definition
3. Remove word
4. Lookup word
5. Quit

Type in a number (1-5): 2
Add definition
Word: Python
Definition: A snake, a programming language, and a British comedy.
Type in a number (1-5): 2
Add definition
Word: Dictionary
Definition: A book where words are defined.
Type in a number (1-5): 1
Definitions:
Python: A snake, a programming language, and a British comedy.
Dictionary: A book where words are defined.

Type in a number (1-5): 4
Lookup Word
Word: Python
The definition of Python is: A snake, a programming language, and a British comedy.
Type in a number (1-5): 3
Remove Word
Word: Dictionary
Dictionary was removed.
Type in a number (1-5): 1
Definitions:
Python: A snake, a programming language, and a British comedy. 
Type in a number (1-5): 5

This program is similar to the name list from the earlier chapter on lists (note that lists use indexes and dictionaries don't). Here's how the program works:

  • First the function print_menu is defined. print_menu just prints a menu that is later used twice in the program.
  • Next comes the funny looking line words = {}. All that line does is tell Python that words is a dictionary.
  • The next few lines just make the menu work.
for x in words.keys():
    print x, ": ", words[x]
  • This goes through the dictionary and prints all the information. The function words.keys() returns a list that is then used by the for loop. The list returned by keys() is not in any particular order so if you want it in alphabetic order it must be sorted. Similar to lists the statement words[x] is used to access a specific member of the dictionary. Of course in this case x is a string.
  • Next the line words[name] = means adds a word and definition to the dictionary. If name is already in the dictionary means replaces whatever was there before.
if name in words:
    del words[name]
  • See if name is in words and remove it if it is. The expression name in words returns true if name is a key in words but otherwise returns false. The line del words[name] removes the key name and the value associated with that key.
if name in words:
    print "The definition of ", name, " is: ", words[name]
  • Check to see if words has a certain key and if it does prints out the definition associated with it.
  • Lastly if the menu choice is invalid it reprints the menu for your viewing pleasure.

A recap: Dictionaries have keys and values. Keys can be strings or numbers. Keys point to values. Values can be any type of variable (including lists or even dictionaries (those dictionaries or lists of course can contain dictionaries or lists themselves (scary right? :-) )). Here is an example of using a list in a dictionary:

max_points = [25, 25, 50, 25, 100]
assignments = ['hw ch 1', 'hw ch 2', 'quiz   ', 'hw ch 3', 'test']
students = {'#Max': max_points}

def print_menu():
    print "1. Add student"
    print "2. Remove student"
    print "3. Print grades"
    print "4. Record grade"
    print "5. Print Menu"
    print "6. Exit"

def print_all_grades():
    print '\t',
    for i in range(len(assignments)):
        print assignments[i], '\t',
    print
    keys = students.keys()
    keys.sort()
    for x in keys:
        print x, '\t',
        grades = students[x]
        print_grades(grades)

def print_grades(grades):
    for i in range(len(grades)):
        print grades[i], '\t', '\t',
    print

print_menu()
menu_choice = 0
while menu_choice != 6:
    print
    menu_choice = input("Menu Choice (1-6): ")
    if menu_choice == 1:
        name = raw_input("Student to add: ")
        students[name] = [0] * len(max_points)
    elif menu_choice == 2:
        name = raw_input("Student to remove: ")
        if name in students:
            del students[name]
        else:
            print "Student:", name, "not found"
    elif menu_choice == 3:
        print_all_grades()
    elif menu_choice == 4:
        print "Record Grade"
        name = raw_input("Student: ")
        if name in students:
            grades = students[name]
            print "Type in the number of the grade to record"
            print "Type a 0 (zero) to exit"
            for i in range(len(assignments)):
                print i + 1, assignments[i], '\t',
            print
            print_grades(grades)
            which = 1234
            while which != -1:
                which = input("Change which Grade: ")
                which = which - 1
                if 0 <= which < len(grades):
                    grade = input("Grade: ")
                    grades[which] = grade
                elif which != -1:
                    print "Invalid Grade Number"
        else:
            print "Student not found"
    elif menu_choice != 6:
        print_menu()

and here is a sample output:

1. Add student
2. Remove student
3. Print grades
4. Record grade
5. Print Menu
6. Exit

Menu Choice (1-6): 3
       hw ch 1         hw ch 2         quiz            hw ch 3         test 
#Max    25              25              50              25              100 

Menu Choice (1-6): 5
1. Add student
2. Remove student
3. Print grades
4. Record grade
5. Print Menu
6. Exit

Menu Choice (1-6): 1
Student to add: Bill

Menu Choice (1-6): 4
Record Grade
Student: Bill
Type in the number of the grade to record
Type a 0 (zero) to exit
1   hw ch 1     2   hw ch 2     3   quiz        4   hw ch 3     5   test 
0               0               0               0               0 
Change which Grade: 1
Grade: 25
Change which Grade: 2
Grade: 24
Change which Grade: 3
Grade: 45
Change which Grade: 4
Grade: 23
Change which Grade: 5
Grade: 95
Change which Grade: 0

Menu Choice (1-6): 3
       hw ch 1         hw ch 2         quiz            hw ch 3         test 
#Max    25              25              50              25              100
Bill    25              24              45              23              95 

Menu Choice (1-6): 6

Here's how the program works. Basically the variable students is a dictionary with the keys being the name of the students and the values being their grades. The first two lines just create two lists. The next line students = {'#Max': max_points} creates a new dictionary with the key {#Max} and the value is set to be [25, 25, 50, 25, 100], since thats what max_points was when the assignment is made (I use the key #Max since # is sorted ahead of any alphabetic characters). Next print_menu is defined. Next the print_all_grades function is defined in the lines:

def print_all_grades():
    print '\t',
    for i in range(len(assignments)):
        print assignments[i], '\t',
    print
    keys = students.keys()
    keys.sort()
    for x in keys:
        print x, '\t',
        grades = students[x]
        print_grades(grades)

Notice how first the keys are gotten out of the students dictionary with the keys function in the line keys = students.keys(). keys is a list so all the functions for lists can be used on it. Next the keys are sorted in the line keys.sort() since it is a list. for is used to go through all the keys. The grades are stored as a list inside the dictionary so the assignment grades = students[x] gives grades the list that is stored at the key x. The function print_grades just prints a list and is defined a few lines later.

The later lines of the program implement the various options of the menu. The line students[name] = [0] * len(max_points) adds a student to the key of their name. The notation [0] * len(max_points) just creates a list of 0's that is the same length as the max_points list.

The remove student entry just deletes a student similar to the telephone book example. The record grades choice is a little more complex. The grades are retrieved in the line grades = students[name] gets a reference to the grades of the student name. A grade is then recorded in the line grades[which] = grade. You may notice that grades is never put back into the students dictionary (as in no students[name] = grades). The reason for the missing statement is that grades is actually another name for students[name] and so changing grades changes student[name].

Dictionaries provide a easy way to link keys to values. This can be used to easily keep track of data that is attached to various keys.