
- Python 資料結構和演算法教程
- Python - DS 首頁
- Python - DS 簡介
- Python - DS 環境
- Python - 陣列
- Python - 列表
- Python - 元組
- Python - 字典
- Python - 二維陣列
- Python - 矩陣
- Python - 集合
- Python - 對映
- Python - 連結串列
- Python - 棧
- Python - 佇列
- Python - 雙端佇列
- Python - 高階連結串列
- Python - 雜湊表
- Python - 二叉樹
- Python - 搜尋樹
- Python - 堆
- Python - 圖
- Python - 演算法設計
- Python - 分治法
- Python - 遞迴
- Python - 回溯法
- Python - 排序演算法
- Python - 搜尋演算法
- Python - 圖演算法
- Python - 演算法分析
- Python - 大O表示法
- Python - 演算法類
- Python - 均攤分析
- Python - 演算法論證
- Python 資料結構與演算法有用資源
- Python - 快速指南
- Python - 有用資源
- Python - 討論
Python - 雜湊表
雜湊表是一種資料結構,其中資料元素的地址或索引值由雜湊函式生成。這使得訪問資料更快,因為索引值充當資料值的鍵。換句話說,雜湊表儲存鍵值對,但鍵是透過雜湊函式生成的。
因此,資料元素的搜尋和插入函式變得更快,因為鍵值本身成為儲存資料的陣列的索引。
在 Python 中,字典資料型別表示雜湊表的實現。字典中的鍵滿足以下要求。
字典的鍵是可雜湊的,即它們是由雜湊函式生成的,該函式為提供給雜湊函式的每個唯一值生成唯一的結果。
字典中資料元素的順序是不固定的。
因此,我們看到如下使用字典資料型別實現雜湊表。
訪問字典中的值
要訪問字典元素,您可以使用熟悉的方括號以及鍵來獲取其值。
示例
# Declare a dictionary dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'} # Accessing the dictionary with its key print ("dict['Name']: ", dict['Name']) print ("dict['Age']: ", dict['Age'])
輸出
當執行上述程式碼時,它會產生以下結果:
dict['Name']: Zara dict['Age']: 7
更新字典
您可以透過新增新條目或鍵值對、修改現有條目或刪除現有條目來更新字典,如下面的簡單示例所示:
示例
# Declare a dictionary dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'} dict['Age'] = 8; # update existing entry dict['School'] = "DPS School"; # Add new entry print ("dict['Age']: ", dict['Age']) print ("dict['School']: ", dict['School'])
輸出
當執行上述程式碼時,它會產生以下結果:
dict['Age']: 8 dict['School']: DPS School
刪除字典元素
您可以刪除單個字典元素或清除字典的全部內容。您還可以透過單個操作刪除整個字典。要顯式刪除整個字典,只需使用 del 語句。
示例
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'} del dict['Name']; # remove entry with key 'Name' dict.clear(); # remove all entries in dict del dict ; # delete entire dictionary print ("dict['Age']: ", dict['Age']) print ("dict['School']: ", dict['School'])
輸出
這會產生以下結果。請注意,會引發異常,因為在 del dict 之後,字典不再存在。
dict['Age']: dict['Age'] dict['School']: dict['School']
廣告