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:
defprint_menu():print'1. Print Dictionary'print'2. Add definition'print'3. Remove word'print'4. Lookup word'print'5. Quit'printwords={}menu_choice=0print_menu()whilemenu_choice!=5:menu_choice=input("Type in a number (1-5): ")ifmenu_choice==1:print"Definitions:"forxinwords.keys():printx,": ",words[x]printelifmenu_choice==2:print"Add definition"name=raw_input("Word: ")means=raw_input("Definition: ")words[name]=meanselifmenu_choice==3:print"Remove word"name=raw_input("Word: ")ifnameinwords:delwords[name]printname," was removed."else:printname," was not found."elifmenu_choice==4:print"Lookup Word"name=raw_input("Word: ")ifnameinwords:print"The definition of ",name," is: ",words[name]else:print"No definition for ",name," was found."elifmenu_choice!=5:print_menu()
And here is my output:
1. Print Dictionary2. Add definition3. Remove word4. Lookup word5. QuitType in a number (1-5):2Add definitionWord:PythonDefinition:A snake, a programming language, and a British comedy.Type in a number (1-5):2Add definitionWord:DictionaryDefinition:A book where words are defined.Type in a number (1-5):1Definitions:Python: A snake, a programming language, and a British comedy.Dictionary: A book where words are defined.Type in a number (1-5):4Lookup WordWord:PythonThe definition of Python is: A snake, a programming language, and a British comedy.Type in a number (1-5):3Remove WordWord:DictionaryDictionary was removed.Type in a number (1-5):1Definitions: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:
print_menu
is defined.print_menu
just prints a menu that is later used twice in the program.words = {}
. All that line does is tell Python thatwords
is a dictionary.forxinwords.keys():printx,": ",words[x]
words.keys()
returns a list that is then used by thefor
loop. The list returned bykeys()
is not in any particular order so if you want it in alphabetic order it must be sorted. Similar to lists the statementwords[x]
is used to access a specific member of the dictionary. Of course in this casex
is a string.words[name] = means
adds a word and definition to the dictionary. Ifname
is already in the dictionarymeans
replaces whatever was there before.ifnameinwords:delwords[name]
name in words
returns true ifname
is a key inwords
but otherwise returns false. The linedel words[name]
removes the keyname
and the value associated with that key.ifnameinwords:print"The definition of ",name," is: ",words[name]
A recap: Dictionaries have keys and values. Keys can be strings ornumbers. Keys point to values. Values can be any type of variable(including lists or even dictionaries (those dictionaries or lists ofcourse 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}defprint_menu():print"1. Add student"print"2. Remove student"print"3. Print grades"print"4. Record grade"print"5. Print Menu"print"6. Exit"defprint_all_grades():print'\t',foriinrange(len(assignments)):printassignments[i],'\t',printkeys=students.keys()keys.sort()forxinkeys:printx,'\t',grades=students[x]print_grades(grades)defprint_grades(grades):foriinrange(len(grades)):printgrades[i],'\t','\t',printprint_menu()menu_choice=0whilemenu_choice!=6:printmenu_choice=input("Menu Choice (1-6): ")ifmenu_choice==1:name=raw_input("Student to add: ")students[name]=[0]*len(max_points)elifmenu_choice==2:name=raw_input("Student to remove: ")ifnameinstudents:delstudents[name]else:print"Student:",name,"not found"elifmenu_choice==3:print_all_grades()elifmenu_choice==4:print"Record Grade"name=raw_input("Student: ")ifnameinstudents:grades=students[name]print"Type in the number of the grade to record"print"Type a 0 (zero) to exit"foriinrange(len(assignments)):printi+1,assignments[i],'\t',printprint_grades(grades)which=1234whilewhich!=-1:which=input("Change which Grade: ")which=which-1if0<=which<len(grades):grade=input("Grade: ")grades[which]=gradeelifwhich!=-1:print"Invalid Grade Number"else:print"Student not found"elifmenu_choice!=6:print_menu()
and here is a sample output:
1. Add student2. Remove student3. Print grades4. Record grade5. Print Menu6. ExitMenu 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):51. Add student2. Remove student3. Print grades4. Record grade5. Print Menu6. ExitMenu Choice (1-6):1Student to add:BillMenu Choice (1-6):4Record GradeStudent:BillType in the number of the grade to recordType a 0 (zero) to exit1 hw ch 1 2 hw ch 2 3 quiz 4 hw ch 3 5 test 0 0 0 0 0 Change which Grade:1Grade:25Change which Grade:2Grade:24Change which Grade:3Grade:45Change which Grade:4Grade:23Change which Grade:5Grade:95Change which Grade:0Menu Choice (1-6):3 hw ch 1 hw ch 2 quiz hw ch 3 test #Max 25 25 50 25 100Bill 25 24 45 23 95 Menu Choice (1-6):6
Here's how the program works. Basically the variablestudents
isa dictionary with the keys being the name of the students and thevalues being their grades. The first two lines just create two lists.The next linestudents = {'#Max': max_points}
creates a newdictionary with the key {#Max
} and the value is set to be[25, 25, 50, 25, 100]
, since thats whatmax_points
was when the assignment is made (I use the key#Max
since#
is sortedahead of any alphabetic characters). Nextprint_menu
isdefined. Next theprint_all_grades
function is defined in thelines:
defprint_all_grades():print'\t',foriinrange(len(assignments)):printassignments[i],'\t',printkeys=students.keys()keys.sort()forxinkeys:printx,'\t',grades=students[x]print_grades(grades)
Notice how first the keys are gotten out of thestudents
dictionary with thekeys
function in the linekeys = students.keys()
.keys
is a list so all the functions for lists can be used on it. Next the keys are sorted in the linekeys.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 assignmentgrades = students[x]
givesgrades
the list that is stored at the keyx
. The functionprint_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 linestudents[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 themax_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 linegrades = students[name]
gets a reference to the grades of the studentname
. A grade is then recorded in the linegrades[which] = grade
. You may notice thatgrades
is never put back into the students dictionary (as in nostudents[name] = grades
). The reason for the missing statement is thatgrades
is actually another name forstudents[name]
and so changinggrades
changesstudent[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.