定义
字典的定义,同样使用{},不过存储的元素是一个个的: 键值对(key不能重复,重复添加等同于覆盖原有数据)(通过字典可以通过key取出value)字典的key和value可以是任意数据类型。(key不能是字典)
dict1={'yy':100,'ss':99,'abc':88}#定义字典变量
my_dict={}
my_dict1=dict()#定义空字典
字典的操作
1.从字典中基于key找到value
语法:变量=dict["key"]
dict1={'yy':100,'ss':99,'abc':88}
print(score)#结果为100
2.字典的嵌套
stu_score={
"yy":{
"语文":99,"英语":100,"数学":88
},"ss":{
"语文":100,"英语":99,"数学":96
}
}
ss_e_score=stu_score["ss"]["英语"]
print(ss_e_score)#结果是99
3.字典的修改
1.新增语法:字典[Key]=Value
结果:字典被修改,新增了元素
2.更新元素语法:字典[原来的key]=Value
3.删除语法:字典.pop(“key”)
4.清空元素语法:字典.clear()
5.获取字典全部key:字典:keys()
6.计算字典内元素数量:len(字典)
4.字典的遍历(因为不支持下标索引,所以不支持while循环)
方式1:通过获取到全部的key来完成遍历
stu_score={
"yy":{
"语文":99,"英语":100,"数学":88
},"ss":{
"语文":100,"英语":99,"数学":96
}
}keys=stu_score.keys()
print(f"字典的全部keys是:{keys}")
for key in keys:
print(f"字典的key是:{key}")
print(f"字典的value是:{stu_score[key]}")
方式2:直接对字典进行for循环,每一次循环都是直接得到key
stu_score={
"yy":{
"语文":99,"英语":100,"数学":88
},"ss":{
"语文":100,"英语":99,"数学":96
}
}
for key in stu_score:
print(f"字典的key是:{key}")
print(f"字典的value是:{stu_score[key]}")
5.统计字典元素(len)
语法:len(字典)
练习
有如下员工信息,请使用字典完成数据的记录
并通过for循环,对所有级别为1级的员工,级别上升1级,薪水增加1000元
staff_sal={
"王力鸿":
{"部门":"科技部","工资":3000,"级别":1},
"周杰轮":
{"部门":"市场部","工资":5000,"级别":2},
"林俊节":
{"部门":"市场部","工资":7000,"级别":3},
"张学油":
{"部门":"科技部","工资":4000,"级别":1},
"刘德滑":
{"部门":"市场部","工资":6000,"级别":2},
}
staff_sal2={
"王力鸿":
{"部门":"科技部","工资":3000,"级别":1},
"周杰轮":
{"部门":"市场部","工资":5000,"级别":2},
"林俊节":
{"部门":"市场部","工资":7000,"级别":3},
"张学油":
{"部门":"科技部","工资":4000,"级别":1},
"刘德滑":
{"部门":"市场部","工资":6000,"级别":2},
}
for key in staff_sal:
jibie=staff_sal[key]["级别"]
gongzi=staff_sal[key]["工资"]
if jibie==1:
xinjiebie=jibie+1
xingongzi=gongzi+1000
staff_sal2[key]["级别"]=xinjiebie
staff_sal2[key]["工资"]=xingongzi
print(f"全部员工当前信息如下:{staff_sal}")
print(f"全部员工升职之后信息如下:{staff_sal2}")