散列表(也叫哈希表)是一種數(shù)據(jù)結(jié)構(gòu),其數(shù)據(jù)元素的地址或索引值由散列函數(shù)生成。 這使得訪問數(shù)據(jù)的速度更快,因為索引值是數(shù)據(jù)值的關(guān)鍵字。 換句話說,哈希表存儲鍵值對,但鍵是通過哈希函數(shù)生成的。
因此,數(shù)據(jù)元素的搜索和插入函數(shù)變得更快,因為鍵值本身成為存儲數(shù)據(jù)的數(shù)組的索引。
在Python中,字典數(shù)據(jù)類型表示哈希表的實現(xiàn)。字典中的鍵滿足以下要求。
所以可通過使用下面的字典數(shù)據(jù)類型來看到哈希表的實現(xiàn)。
要訪問字典元素,可以使用熟悉的方括號 - [] 來獲取它的值。
# Declare a dictionary
dict = {'Name': 'maxsu', 'Age': 27, 'Class': 'First'}
# Accessing the dictionary with its key
print ("dict['Name']: ", dict['Name'])
print ("dict['Age']: ", dict['Age'])
執(zhí)行上面示例代碼,得到以下結(jié)果 -
dict['Name']: maxsu
dict['Age']: 27
可以通過添加新條目或鍵值對,修改現(xiàn)有條目或刪除現(xiàn)有條目來更新字典,如簡單示例中所示 -
# Declare a dictionary
dict = {'Name': 'Maxsu', 'Age': 26, 'Class': 'First'}
dict['Age'] = 8; # update existing entry
dict['School'] = "第一中學(xué)"; # Add new entry
print ("dict['Age']: ", dict['Age'])
print ("dict['School']: ", dict['School'])
執(zhí)行上面示例代碼,得到以下結(jié)果 -
dict['Age']: 8
dict['School']: 第一中學(xué)
可以刪除單個字典元素,也可以清除字典的全部內(nèi)容。 也可以在一個操作中刪除整個字典。 要顯式刪除整個字典,只需使用del語句。 參考以下代碼 -
dict = {'Name': 'Maxsu', 'Age': 26, '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'])
執(zhí)行上面示例代碼,得到以下結(jié)果 -
請注意,由于在執(zhí)行
del語句之后,字典不再存在之后會引發(fā)異常。
Traceback (most recent call last):
File "F:\worksp\pythonds\test.py", line 7, in <module>
print ("dict['Age']: ", dict['Age'])
TypeError: 'type' object is not subscriptable