跳转到内容

面向非程序员的 Python 2.6 教程/字典

来自维基教科书,开放的书籍,面向开放的世界

本章节将介绍字典。如果您打开一本字典,您应该注意到每个条目都包含两个部分,一个单词和该单词的定义。单词是找到单词含义的关键,而单词的含义被认为是该键的值。在 Python 中,字典有键和值。键用于查找值。以下是一个使用字典的示例

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()

这是我的输出

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

该程序类似于之前章节中列表的名称列表(请注意,列表使用索引,而字典不使用索引)。以下是程序的工作原理

  • 首先定义函数 print_menuprint_menu 只是打印一个菜单,该菜单稍后在程序中使用两次。
  • 接下来是奇怪的代码行 words = {}。该行只是告诉 Python words 是一个字典。
  • 接下来的几行只是让菜单正常工作。
for x in words.keys():
    print x, ": ", words[x]
  • 这会遍历字典并打印所有信息。函数 words.keys() 返回一个列表,该列表随后被 for 循环使用。keys() 返回的列表没有特定的顺序,因此如果您想要按字母顺序排列,则必须对其进行排序。类似于列表,语句 words[x] 用于访问字典的特定成员。当然,在这种情况下,x 是一个字符串。
  • 接下来,代码行 words[name] = means 将一个单词和定义添加到字典中。如果 name 已经存在于字典中,means 将替换之前存在的内容。
if name in words:
    del words[name]
  • 查看 name 是否在 words 中,如果在的话就将其移除。表达式 name in words 如果 namewords 中的键,则返回 True,否则返回 False。代码行 del words[name] 删除键 name 以及与该键关联的值。
if name in words:
    print "The definition of ", name, " is: ", words[name]
  • 检查 words 是否包含某个键,如果包含的话,就打印与之关联的定义。
  • 最后,如果菜单选择无效,则会重新打印菜单以供您查看。

回顾:字典有键和值。键可以是字符串或数字。键指向值。值可以是任何类型的变量(包括列表,甚至字典(这些字典或列表当然可以包含字典或列表本身(吓人吗?:-) ))。以下是用列表在字典中使用的一个示例

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()

这是样本输出

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

以下是程序的工作原理。基本上,变量 students 是一个字典,键是学生的姓名,值是他们的成绩。前两行只是创建两个列表。下一行 students = {'#Max': max_points} 创建一个新的字典,键为 {#Max},值为 [25, 25, 50, 25, 100],因为这是 max_points 在赋值时的情况(我使用键 #Max,因为 # 排列在任何字母字符之前)。接下来定义 print_menu。接下来,print_all_grades 函数在以下几行中定义

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)

注意,首先使用 keys 函数从 students 字典中获取键,代码行 keys = students.keys()keys 是一个列表,因此所有列表函数都可以用于它。接下来,键在代码行 keys.sort() 中进行排序,因为它是列表。for 用于遍历所有键。成绩作为列表存储在字典中,因此赋值 grades = students[x] 会使 grades 等于存储在键 x 处的列表。函数 print_grades 只是打印一个列表,并在接下来的几行中定义。

程序的后续代码行实现了菜单的各种选项。代码行 students[name] = [0] * len(max_points) 将学生添加到其姓名的键中。符号 [0] * len(max_points) 只是创建了一个与 max_points 列表长度相同的 0 列表。

移除学生条目只是删除学生,类似于电话簿示例。记录成绩选项稍微复杂一些。成绩在代码行 grades = students[name] 中检索,获取学生 name 成绩的引用。然后,在代码行 grades[which] = grade 中记录成绩。您可能注意到,grades 从未放回 students 字典中(如没有 students[name] = grades)。缺少该语句的原因是,grades 实际上是 students[name] 的另一个名称,因此更改 grades 会更改 student[name]

字典提供了一种简单的方法来将键与值关联起来。这可以用来轻松跟踪附加到各个键的数据。

华夏公益教科书