面向非程式設計師的 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_menu。print_menu只是列印一個選單,該選單稍後在程式中使用兩次。 - 接下來是奇怪的程式碼行
words = {}。該行只是告訴 Pythonwords是一個字典。 - 接下來的幾行只是讓選單正常工作。
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如果name是words中的鍵,則返回 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]。
字典提供了一種簡單的方法來將鍵與值關聯起來。這可以用來輕鬆跟蹤附加到各個鍵的資料。