一、字典是什麼以及如何創建
Python字典是一種可變、無序的數據類型,它由鍵值對構成,每個鍵值對之間用逗號分隔,整個字典被花括弧{}包括。鍵必須是唯一的,且不可變對象,如字元串,數字或元組。值則可以是任意對象。
# 創建一個空字典 dict1 = {} # 創建一個有初始值的字典 dict2 = {'apple': 1, 'banana': 2, 'orange': 3} # 使用dict()函數創建字典 dict3 = dict([('apple', 1), ('banana', 2), ('orange', 3)]) # 使用字典推導式創建字典 dict4 = {x: x**2 for x in (2, 4, 6)} # 輸出字典 print(dict1) print(dict2) print(dict3) print(dict4)
二、字典的查詢和修改
字典中的鍵值對可以通過鍵來查詢或修改。
# 查詢字典中的值 dict = {'apple': 1, 'banana': 2, 'orange': 3} print(dict['apple']) # 輸出1 # 修改字典中的值 dict['banana'] = 5 print(dict) # 輸出{'apple': 1, 'banana': 5, 'orange': 3}
三、字典的刪除和清空
可以使用del語句刪除字典中的鍵值對,也可以使用clear()方法清空整個字典。
# 刪除字典中的鍵值對 dict = {'apple': 1, 'banana': 2, 'orange': 3} del dict['apple'] print(dict) # 輸出{'banana': 2, 'orange': 3} # 清空整個字典 dict.clear() print(dict) # 輸出{}
四、字典的遍歷
使用for循環可以遍歷字典中的鍵值對,也可以使用keys()方法、values()方法和items()方法分別遍歷鍵、值和鍵值對。
# 遍歷字典中的鍵值對 dict = {'apple': 1, 'banana': 2, 'orange': 3} for key, value in dict.items(): print(key, value) # 遍歷字典中的鍵 for key in dict.keys(): print(key) # 遍歷字典中的值 for value in dict.values(): print(value)
五、字典的複製
使用copy()方法可以複製一個字典,分為淺複製和深複製。
# 淺複製 dict1 = {'apple': 1, 'banana': [2, 3, 4], 'orange': 5} dict2 = dict1.copy() dict2['banana'].append(6) print(dict1) # 輸出{'apple': 1, 'banana': [2, 3, 4, 6], 'orange': 5} print(dict2) # 輸出{'apple': 1, 'banana': [2, 3, 4, 6], 'orange': 5} # 深複製 import copy dict1 = {'apple': 1, 'banana': [2, 3, 4], 'orange': 5} dict2 = copy.deepcopy(dict1) dict2['banana'].append(6) print(dict1) # 輸出{'apple': 1, 'banana': [2, 3, 4], 'orange': 5} print(dict2) # 輸出{'apple': 1, 'banana': [2, 3, 4, 6], 'orange': 5}
六、字典的常用方法
Python字典還提供了一些常用方法,如get()方法、setdefault()方法、pop()方法、popitem()方法等。
# get()方法:根據鍵獲取值,如果不存在則返回默認值 dict = {'apple': 1, 'banana': 2, 'orange': 3} print(dict.get('apple')) # 輸出1 print(dict.get('watermelon', 0)) # 輸出0 # setdefault()方法:根據鍵獲取值,如果不存在則設置默認值 dict.setdefault('watermelon', 4) print(dict) # 輸出{'apple': 1, 'banana': 2, 'orange': 3, 'watermelon': 4} # pop()方法:根據鍵刪除值,並返回該值 value = dict.pop('banana') print(value) # 輸出2 print(dict) # 輸出{'apple': 1, 'orange': 3, 'watermelon': 4} # popitem()方法:隨機刪除並返回一個鍵值對 item = dict.popitem() print(item) # 輸出('watermelon', 4) print(dict) # 輸出{'apple': 1, 'orange': 3}
七、字典的應用
Python字典在實際應用中非常廣泛,可以用於存儲任何類型的數據,如學生信息、網站用戶信息、郵件列表等。
# 學生信息管理系統 students = {'1001': {'name': 'Tom', 'age': 18, 'gender': 'male'}, '1002': {'name': 'Lucy', 'age': 19, 'gender': 'female'}, '1003': {'name': 'Jack', 'age': 20, 'gender': 'male'}} print(students['1001']['name']) # 輸出Tom
八、總結
Python字典是一種非常強大的數據類型,它能夠高效存儲、查詢和操作數據,可以用於解決眾多實際問題。在使用字典時,我們需要注意其鍵必須是唯一的、不可變的,而值則可以是任何對象。同時,字典提供了豐富的方法和操作,如遍歷、刪除、複製、查詢等。我們需要根據實際需求靈活運用這些功能,以提高代碼的效率和可讀性。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/187553.html