📄 node13.html
字号:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<!-- saved from url=(0062)http://www.honors.montana.edu/~jjc/easytut/easytut/node13.html -->
<!--Converted with LaTeX2HTML 99.2beta6 (1.42)original version by: Nikos Drakos, CBLU, University of Leeds* revised and updated by: Marcus Hennecke, Ross Moore, Herb Swan* with significant contributions from: Jens Lippmann, Marek Rouchal, Martin Wilck and others --><HTML><HEAD><TITLE>Dictionaries</TITLE>
<META content=Dictionaries name=description>
<META content=easytut name=keywords>
<META content=document name=resource-type>
<META content=global name=distribution>
<META content="text/html; charset=iso-8859-1" http-equiv=Content-Type>
<META content="MSHTML 5.00.2614.3500" name=GENERATOR>
<META content=text/css http-equiv=Content-Style-Type><LINK
href="node13_files/easytut.css" rel=STYLESHEET><LINK href="node14.html"
rel=next><LINK href="node12.html" rel=previous><LINK href="easytut.html"
rel=up><LINK href="node14.html" rel=next></HEAD>
<BODY><!--Navigation Panel--><A
href="http://www.honors.montana.edu/~jjc/easytut/easytut/node14.html"
name=tex2html318><IMG align=bottom alt=next border=0 height=24
src="node13_files/next.png" width=37></A> <A
href="http://www.honors.montana.edu/~jjc/easytut/easytut/easytut.html"
name=tex2html314><IMG align=bottom alt=up border=0 height=24
src="node13_files/up.png" width=26></A> <A
href="http://www.honors.montana.edu/~jjc/easytut/easytut/node12.html"
name=tex2html308><IMG align=bottom alt=previous border=0 height=24
src="node13_files/prev.png" width=63></A> <A
href="http://www.honors.montana.edu/~jjc/easytut/easytut/node2.html"
name=tex2html316><IMG align=bottom alt=contents border=0 height=24
src="node13_files/contents.png" width=65></A> <BR><B>Next:</B> <A
href="http://www.honors.montana.edu/~jjc/easytut/easytut/node14.html"
name=tex2html319>Using Modules</A> <B>Up:</B> <A
href="http://www.honors.montana.edu/~jjc/easytut/easytut/easytut.html"
name=tex2html315>Non-Programmers Tutorial For Python</A> <B>Previous:</B> <A
href="http://www.honors.montana.edu/~jjc/easytut/easytut/node12.html"
name=tex2html309>Boolean Expressions</A> <B><A
href="http://www.honors.montana.edu/~jjc/easytut/easytut/node2.html"
name=tex2html317>Contents</A></B> <BR><BR><!--End of Navigation Panel-->
<H1><A name=SECTION001300000000000000000>Dictionaries</A> </H1>This chapter is
about dictionaries. Dictionaries have keys and values. The keys are used to find
the values. Here is an example of a dictionary in use: <PRE>def print_menu():
print '1. Print Phone Numbers'
print '2. Add a Phone Number'
print '3. Remove a Phone Number'
print '4. Lookup a Phone Number'
print '5. Quit'
print
numbers = {}
menu_choice = 0
print_menu()
while menu_choice != 5:
menu_choice = input("Type in a number (1-5):")
if menu_choice == 1:
print "Telephone Numbers:"
for x in numbers.keys():
print "Name: ",x," \tNumber: ",numbers[x]
print
elif menu_choice == 2:
print "Add Name and Number"
name = raw_input("Name:")
phone = raw_input("Number:")
numbers[name] = phone
elif menu_choice == 3:
print "Remove Name and Number"
name = raw_input("Name:")
if numbers.has_key(name):
del numbers[name]
else:
print name," was not found"
elif menu_choice == 4:
print "Lookup Number"
name = raw_input("Name:")
if numbers.has_key(name):
print "The number is",numbers[name]
else:
print name," was not found"
elif menu_choice != 5:
print_menu()
</PRE>And here is my output: <PRE>1. Print Phone Numbers
2. Add a Phone Number
3. Remove a Phone Number
4. Lookup a Phone Number
5. Quit
Type in a number (1-5):2
Add Name and Number
Name:Joe
Number:545-4464
Type in a number (1-5):2
Add Name and Number
Name:Jill
Number:979-4654
Type in a number (1-5):2
Add Name and Number
Name:Fred
Number:132-9874
Type in a number (1-5):1
Telephone Numbers:
Name: Jill Number: 979-4654
Name: Joe Number: 545-4464
Name: Fred Number: 132-9874
Type in a number (1-5):4
Lookup Number
Name:Joe
The number is 545-4464
Type in a number (1-5):3
Remove Name and Number
Name:Fred
Type in a number (1-5):1
Telephone Numbers:
Name: Jill Number: 979-4654
Name: Joe Number: 545-4464
Type in a number (1-5):5
</PRE>This program is similar to the name list earlier in the the chapter on
lists. Heres how the program works. First the function <CODE>print_menu</CODE>
is defined. <CODE>print_menu</CODE> just prints a menu that is later used twice
in the program. Next comes the funny looking line <CODE>numbers = {}</CODE>. All
that line does is tell Python that <TT>numbers</TT> is a dictionary. The next
few lines just make the menu work. The lines: <PRE>for x in numbers.keys():
print "Name: ",x," \tNumber: ",numbers[x]
</PRE>go through the dictionary and print all the information. The function
<TT>numbers.keys()</TT> returns a list that is then used by the <TT>for</TT>
loop. The list returned by <TT>keys</TT> is not in any particular order so if
you want it in alphabetic order it must be sorted. Similar to lists the
statement <TT>numbers[x]</TT> is used to access a specific member of the
dictionary. Of course in this case <TT>x</TT> is a string. Next the line
<TT>numbers[name] = phone</TT> adds a name and phone number to the dictionary.
If <TT>name</TT> had already been in the dictionary <TT>phone</TT> would replace
whatever was there before. Next the lines: <PRE>if numbers.has_key(name):
del numbers[name]
</PRE>see if a name is in the dictionary and remove it if it is. The function
<CODE>numbers.has_key(name)</CODE> returns true if <TT>name</TT> is in
<TT>numbers</TT> but other wise returns false. The line <TT>del
numbers[name]</TT> removes the key <TT>name</TT> and the value associated with
that key. The lines: <PRE>if numbers.has_key(name):
print "The number is",numbers[name]
</PRE>check to see if the dictionary has a certain key and if it does prints out
the number associated with it. Lastly if the menu choice is invalid it reprints
the menu for your viewing pleasure.
<P><A name=firstgrades></A>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: <PRE>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"
</PRE><PRE>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)
</PRE><PRE>def print_grades(grades):
for i in range(len(grades)):
print grades[i],'\t\t',
print
</PRE><PRE>
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 students.has_key(name):
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 students.has_key(name):
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()
</PRE>and here is a sample output: <PRE>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
</PRE><PRE>Menu Choice (1-6):6
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
</PRE><PRE>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
</PRE><PRE>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
</PRE>Heres how the program works. Basically the variable <TT>students</TT> 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
<CODE>SPMquot</CODE>students = '#Max':max_points" creates a new dictionary with
the key <CODE>#Max</CODE> and the value is set to be <TT>[25,25,50,25,100]</TT>
(since thats what <CODE>max_points</CODE> was when the assignment is made) (I
use the key <CODE>#Max</CODE> since <CODE>#</CODE> is sorted ahead of any
alphabetic characters). Next <CODE>print_menu</CODE> is defined. Next the
<CODE>print_all_grades</CODE> function is defined in the lines: <PRE>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)
</PRE>Notice how first the keys are gotten out of the <TT>students</TT>
dictionary with the <TT>keys</TT> function in the line <TT>keys =
students.keys() </TT>. <TT>keys</TT> is a list so all the functions for lists
can be used on it. Next the keys are sorted in the line <TT>keys.sort()</TT>
since it is a list. <TT>for</TT> is used to go through all the keys. The grades
are stored as a list inside the dictionary so the assignment <TT>grades =
students[x]</TT> gives <TT>grades</TT> the list that is stored at the key
<TT>x</TT>. The function <CODE>print_grades</CODE> just prints a list and is
defined a few lines later.
<P>The later lines of the program implement the various options of the menu. The
line <CODE>students[name] = [0]*len(max_points)</CODE> adds a student to the key
of their name. The notation <CODE>[0]*len(max_points)</CODE> just creates a
array of 0's that is the same length as the <CODE>max_points</CODE> list.
<P>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 <TT>grades = students[name]</TT> gets a reference to the
grades of the student <TT>name</TT>. A grade is then recorded in the line
<TT>grades[which] = grade</TT>. You may notice that <TT>grades</TT> is never put
back into the students dictionary (as in no <TT>students[name] = grades</TT>).
The reason for the missing statement is that <TT>grades</TT> is actually another
name for <TT>students[name]</TT> and so changing <TT>grades</TT> changes
<TT>student[name]</TT>.
<P>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.
<P>
<HR>
<!--Navigation Panel--><A
href="http://www.honors.montana.edu/~jjc/easytut/easytut/node14.html"
name=tex2html318><IMG align=bottom alt=next border=0 height=24
src="node13_files/next.png" width=37></A> <A
href="http://www.honors.montana.edu/~jjc/easytut/easytut/easytut.html"
name=tex2html314><IMG align=bottom alt=up border=0 height=24
src="node13_files/up.png" width=26></A> <A
href="http://www.honors.montana.edu/~jjc/easytut/easytut/node12.html"
name=tex2html308><IMG align=bottom alt=previous border=0 height=24
src="node13_files/prev.png" width=63></A> <A
href="http://www.honors.montana.edu/~jjc/easytut/easytut/node2.html"
name=tex2html316><IMG align=bottom alt=contents border=0 height=24
src="node13_files/contents.png" width=65></A> <BR><B>Next:</B> <A
href="http://www.honors.montana.edu/~jjc/easytut/easytut/node14.html"
name=tex2html319>Using Modules</A> <B>Up:</B> <A
href="http://www.honors.montana.edu/~jjc/easytut/easytut/easytut.html"
name=tex2html315>Non-Programmers Tutorial For Python</A> <B>Previous:</B> <A
href="http://www.honors.montana.edu/~jjc/easytut/easytut/node12.html"
name=tex2html309>Boolean Expressions</A> <B><A
href="http://www.honors.montana.edu/~jjc/easytut/easytut/node2.html"
name=tex2html317>Contents</A></B> <!--End of Navigation Panel-->
<ADDRESS>Josh Cogliati <A
href="mailto:jjc@honors.montana.edu">jjc@honors.montana.edu</A>
</ADDRESS></BODY></HTML>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -