Python数据结构教程:哈希(哈希表)
哈希表(也称为哈希表)是一种数据结构,其中其数据元素的地址或索引值由哈希函数生成。这加快了数据访问速度,因为索引值是数据值的关键。换句话说,哈希 表存储键值对,但键是通过 哈希 函数生成的。
这样就加快了数据元素的查找和添加功能,因为键值本身就成为了存储数据的表的索引。
在 Python 中,字典数据类型表示 哈希 数组的实现。字典键满足以下要求。
- 字典键是可散列的,也就是说,它们是用散列函数形成的,该散列函数为输入散列函数的每个唯一值生成唯一的结果。
- 字典中数据元素的顺序不固定。因此,可以使用下面的字典数据类型来查看
哈希 的表实现。
使用字典中的值
字典元素可以与熟悉的括号 - []一起使用来获取其值。
# 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'])
Python运行上面的示例代码并获得以下结果 -
dict['Name']: maxsu
dict['Age']: 27
Shell更新字典元素
可以通过添加现有条目、删除或评估新条目或将现有条目键入字典来更新在简单的示例中显示 -
# Declare a dictionary
dict = {'Name': 'Maxsu', 'Age': 26, 'Class': 'First'}
dict['Age'] = 8; # update existing entry
dict['School'] = "第一中学"; # Add new entry
print ("dict['Age']: ", dict['Age'])
print ("dict['School']: ", dict['School'])
Python执行上面的示例代码会产生以下结果 -
dict['Age']: 8
dict['School']: 第一中学
Shell删除字典元素 或清除单个单词。整个词典的内容。也可以通过一次操作删除整个字典。如果要显式删除整个字典,请使用 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'])
Python
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'])
运行上面的示例代码,得到以下结果 -
注意,在del语句之后,字典是在异常后抛出的。不复存在。
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 版权声明
本文仅代表作者观点,不代表Code前端网立场。
本文系作者Code前端网发表,如需转载,请注明页面地址。
code前端网