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']
廣告