Python数据结构基础知识(4):字典Dictionary/哈希表Hash Table

哈希表是通过哈希函数将数据映射到指定内存空间的一种方式。在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进行访问)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值