Python 3 非程序员教程/字典
本章节介绍字典。字典包含键和值。键用于查找值。以下是一个字典使用的示例
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_menu
。print_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
如果name
在numbers
中则返回真,否则返回假。行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]
。
字典提供了一种将键链接到值简单的方法。这可以用于轻松跟踪附加到各种键的数据。