在 Python 中,字典(dictionary)是一種由鍵值對(key-value pairs)組成的數據結構。字典允許我們使用唯一的鍵(key)來存取對應的值(value),可以理解為一組「鍵與值」的映射關係。它適合用來存儲、查找和管理標識符(如名稱、ID)和數據之間的關聯。
初始化Dictionary內容
student_scores = {"Alice": 85, "Bob": 90, "Charlie": 78, "David": 92} |
使用key來查詢對應內容,並且考慮大小寫關係
student_name = input("Please enter student name:")# 先將輸入參數轉換為小寫student_name_lower = student_name.lower() found = False# Dictionary的內建用法,會返回key-value pairs,# 所以才需要在迴圈內使用name, score去接for name, score in student_scores.items(): if name.lower() == student_name_lower: print(f"{name} score = {score}") found = True breakif not found: print(f"There is no score of {student_name}") |
Dictionary也可以用來統計出現字數
text = "apple orange banana apple banana apple"word_count = {} for word in text.split(): if word in word_count: word_count[word] += 1 else: word_count[word] = 1 |
先將word_count設為空dicrtionary,split函數預設分隔符是空白鍵
上述程式碼會出現結果為{'apple': 3, 'orange': 1, 'banana': 2}
再來Dictionary只要你想可以延伸至好幾層Dictionary,也就是有一層Outer Dictionary + Inner Dictionary
如以下範例,John,是Outer Dictionary的Key, Value是另一層Dictionary,在Inner Dictionary則是有兩組key-value pairs {username, age},分別對應{John, 30}
users = {# Key of Outer Inner Dictionary"John": {"username": "John", "age": 30},"Alice": {"username": "Alice", "age": 28},"Bob": {"username": "Bob", "age": 35},} |
以下是簡單查找這2-level dictionary的範例程式,假設要查找Alice的資訊,一樣考慮大小寫防呆,輸出結果會是username: Alice, age: 28
user_to_query = "alice"user_to_query_lower = user_to_query.lower() found = Falsefor name, info in users.items(): if name.lower() == user_to_query_lower: if name in users: user = info print(f"username: {user['username']}") print(f"age: {user['age']}") found = True breakif not found: print(f"Can't find {user_to_query}") |
如果想用value反查key的話,以下是範例程式,利用list來達成目的,List comprehension是python的語法,一樣使用Dictionary items()內建函數,會返回key, value,在for迴圈使用key, value來接數items的返回,然後比較value以及想反查的employee_name
employee_id = {1001: "Alice", 1002: "Bob", 1003: "Charlie"} employee_name = "Bob"# list comprehensionemployee_id_number = [key for key, value in employee_id.items() if value == employee_name]print(f"{employee_name}'s id = {employee_id_number[0]}") |
Dictionary+List+Tuple也可以使用如下方式,來分類內容,比如students本身為list,list element是tuple,若我想分類得到A的一組,B的一組,C的一組
students = [("Alice", "A"), ("Bob", "B"), ("Charlie", "A"), ("David", "C")] |
可以使用下面範例,grade_groups為空Dictionary,一樣使用student, grade去接students這個list,如果grade這個key還沒出現在Dictionary時,把grade這個key的value設成空list,否則將根據grade這個key將value放進Dictionary,以下程式會出現{'A': ['Alice', 'Charlie'], 'B': ['Bob'], 'C': ['David']}這個結果
grade_groups = {} for student, grade in students: if grade not in grade_groups: grade_groups[grade] = [] grade_groups[grade].append(student) |
student_scores = {"Alice": 85, "Bob": 90, "Charlie": 78, "David": 92} |
最後要插入新Entry的方式為以下方式,這時student_scores會新增一個{key, value} = {"Jasper", 60}的內容,若是想要一次更新多個entries,可以使用update函數,依照下面的程式範例會更新Jim, Steve的內容
# insert a entry to Dictionarystudent_scores["Jasper"] = 60print(student_scores) # insert multiple entries to Dictionarystudent_scores.update({"Jim": 90, "Steve": 90})print(student_scores) |
若是想刪除Dictionary的其中一個內容
可以用del函數,這時student_scores會變成{"Bob": 90, "Charlie": 78, "David": 92}
del student_scores["Alice"] |
另外還有popitem,不過他是使用stack方式先進後出,所以使用popitem會先刪除Dictionary最後一個entry,我們可以用一個新的變數來接住他
remove_item = student_scores.popitem() |
這時remove_item = {"David", 92}
