Python3字典结构

目录

1、先回忆下列表的操作

2、字典结构

3、用字典结构做统计数


1、先回忆下列表的操作

animals=["cat","dog","rabbit"] #找到list中的某个值(第一种方法)
for animal in animals:
    if(animal=="cat"):
        print("Cat found")
animals=["cat","dog","rabbit"] #找到list中的某个值(第二种方法)
if "cat" in animals:
    print("Cat found")
student=["Tom","Jim","Sue","Ann"] #找到某人所得分数
scores=[70,80,85,75]
indexes=[0,1,2,3]
name="Sue
score=0
for i in indexes:
    if student[i]==name:
        score=scores[i]
print(score)

2、字典结构

scores={} #<class 'dict'> Dictionaries 字典结构 key value (键值一一对应)
scores["Jim"]=80
scores["Sue"]=85
scores["Ann"]=75
print(scores.keys()) #dict_keys(['Jim', 'Sue', 'Ann']) 字典中的key
print(scores) #{'Jim': 80, 'Sue': 85, 'Ann': 75} 输出字典中的键和值
print(scores["Sue"]) #输出键所对应的的值 结果为 85
students={"Tom":60,"Jim":70} #创建字典并初始化键值
students["Tom"]=65 #更改字典中某个键的值
print('Tom' in students) #判断键是否在字典中

3、用字典结构做统计数

pantry=["apple","orange","grape","apple","orange","apple","tomato","patato","grape"]
pantry_counts={}
for item in pantry: #对list进行遍历
    if item in pantry_counts:
        pantry_counts[item]=pantry_counts[item]+1
    else:
        pantry_counts[item]=1
print(pantry_counts) #输出结构{'apple': 3, 'orange': 2, 'grape': 2, 'tomato': 1, 'patato': 1}

补充:dict和set

和list比较,dict有以下几个特点:

(1)查找和插入的速度极快,不会随着key的增加而变慢;

(2)需要占用大量的内存,内存浪费多。

而list相反:

(1)查找和插入的时间随着元素的增加而增加;

(2)占用空间小,浪费内存很少。

#set和dict类似,也是一组key的集合,但不存储value。由于key不能重复,所以,在set中,没有重复的key

#set可以看成数学意义上的无序和无重复元素的集合,因此,两个set可以做数学意义上的交集、并集等操作

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Asia-Lee

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值