哈希表是通过哈希函数将数据映射到指定内存空间的一种方式。在Python中哈希表可以通过字典Dictionary来实现。Python字典的作用是将相关信息关联起来。这里有一个键值对的概念,即关键词和相关值所组成的一对小伙伴(key:value)。字典可包含多个键值对,格式如下:
MyDict = {"color": "red", "point": 18}
一、基本操作
1.查找:MyDict[key]
MyDict = {"color": "red", "point": 18}
print(MyDict["color"]) ----------------> red
2.增加:MyDict[key] = value
MyDict = {"color": "red", "point": 18}
MyDict["age"] = 20
print(MyDict["age"]) ------------------> 20
3 .更新:MyDict[key] = value
同增加方法一样,区别是这里的key是字典中已有的:
MyDict = {"color": "red", "point": 18}
MyDict["color"] = green
print(MyDict) ------------------> {"color": "green", "point": 18}
4,删除:MyDict.pop(key)
MyDict = {"color": "red", "point": 18}
MyDict.pop('point')
print(MyDict)
二、遍历
MyDict = {"color": "red", "point": 18}
for key in MyDict:
print(key)
--------------->
color
point
MyDict = {"color": "red", "point": 18}
for value in MyDict.values():
print(value)
------------------->
red
18
MyDict = {"color": "red", "point": 18}
for k, v in MyDict.items():
print(k, v)
------------------>
color red
point 18
三、复杂度/特点
访问Access:
搜索Search:O(1)
插入Insert:O(1) (哈希冲突:O(k) k为冲突元素的个数,通过链表的方式解决冲突)
删除Delete:O(1)
优点:
搜索Search快、插入Insert快、删除Delete快(输入key后通过哈希函数可直接找到对应内存地址)
缺点:
访问access慢(不可通过索引Index进行访问)