跳转到内容

Python 3 非程序员教程/字典

来自 Wikibooks,开放世界中的开放书籍

本章节介绍字典。字典包含键和值。键用于查找值。以下是一个字典使用的示例

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 = int(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 = input("Name: ")
        phone = input("Number: ")
        numbers[name] = phone
    elif menu_choice == 3:
        print("Remove Name and Number")
        name = input("Name: ")
        if name in numbers:
            del numbers[name]
        else:
            print(name, "was not found")
    elif menu_choice == 4:
        print("Lookup Number")
        name = input("Name: ")
        if name in numbers:
            print("The number is", numbers[name])
        else:
            print(name, "was not found")
    elif menu_choice != 5:
        print_menu()

这是我的输出

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

此程序类似于本章前面列表章节中的名称列表。以下是程序的工作原理。首先定义函数print_menuprint_menu 只打印一个菜单,该菜单稍后在程序中使用两次。接下来是看起来很奇怪的行numbers = {}。这行代码所做的只是告诉 Python numbers 是一个字典。接下来的几行只是使菜单正常工作。这些行

for x in numbers.keys():
    print("Name:", x, "\tNumber:", numbers[x])

遍历字典并打印所有信息。函数numbers.keys()返回一个列表,然后由for循环使用。keys()返回的列表没有特定的顺序,因此如果您希望按字母顺序排列,则必须对其进行排序。与列表类似,语句numbers[x]用于访问字典的特定成员。当然,在这种情况下,x是一个字符串。接下来,行numbers[name] = phone将名称和电话号码添加到字典中。如果name已存在于字典中,则phone将替换之前存在的内容。接下来,这些行

if name in numbers:
    del numbers[name]

检查字典中是否存在名称,如果存在则将其删除。运算符name in numbers如果namenumbers中则返回真,否则返回假。行del numbers[name]删除键name以及与该键关联的值。这些行

if name in numbers:
    print("The number is", numbers[name])

检查字典是否包含某个键,如果包含则打印与之关联的数字。最后,如果菜单选择无效,则会重新打印菜单供您查看。

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

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', end=' ')
    for i in range(len(assignments)):
        print(assignments[i], '\t', end=' ')
    print()
    keys = list(students.keys())
    keys.sort()
    for x in keys:
        print(x, '\t', end=' ')
        grades = students[x]
        print_grades(grades)

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

print_menu()
menu_choice = 0
while menu_choice != 6:
    print()
    menu_choice = int(input("Menu Choice (1-6): "))
    if menu_choice == 1:
        name = input("Student to add: ")
        students[name] = [0] * len(max_points)
    elif menu_choice == 2:
        name = 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 = 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', end=' ')
            print()
            print_grades(grades)
            which = 1234
            while which != -1:
                which = int(input("Change which Grade: "))
                which -= 1    #same as which = which - 1
                if 0 <= which < len(grades):
                    grade = int(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',end=" ")
    for i in range(len(assignments)):
        print(assignments[i], '\t',end=" ")
    print()
    keys = list(students.keys())
    keys.sort()
    for x in keys:
        print(x, '\t',end=' ')
        grades = students[x]
        print_grades(grades)

请注意,首先在行keys = list(students.keys())中使用keys函数从students字典中获取键。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[name] = grades一样)。缺少该语句的原因是grades实际上是students[name]的另一个名称,因此更改grades会更改student[name]

字典提供了一种将键链接到值简单的方法。这可以用于轻松跟踪附加到各种键的数据。

Python 3 非程序员教程
 ← 布尔表达式 字典 使用模块 → 
华夏公益教科书