![](https://i-blog.csdnimg.cn/blog_migrate/70932f74d0becec35b3b3876e59a2a54.png)
![](https://i-blog.csdnimg.cn/blog_migrate/40d842b3251ab0228b4d14ed6e0ee762.png)
# 字典
my_dict = {"王昭君": 90, "吉吉国王": 85, "刘禅": 65}
# 定义空字典
my_dict2 = {}
my_dict3 = dict()
print(f"字典1的内容是:{my_dict},类型:{type(my_dict)}")
print(f"字典1的内容是:{my_dict2},类型:{type(my_dict2)}")
print(f"字典1的内容是:{my_dict3},类型:{type(my_dict3)}")
my_dict["王昭君"]
# 字典嵌套
stu_score_dict = {
"王昭君": {
"语文": 85,
"数学": 89,
"英语": 89
}, "吉吉国王": {
"语文": 85,
"数学": 87,
"英语": 56
}, "韩信": {
"语文": 85,
"数学": 100,
"英语": 35
}
}
print(stu_score_dict)
# 获取信息
stu_score_dict["韩信"]["语文"]
# 新增元素=更新元素
stu_score_dict["赵云"] = 66
print(stu_score_dict)
# 删除元素
stu_score_dict.pop("赵云")
print(stu_score_dict)
# 清空元素
stu_score_dict.clear()
print(stu_score_dict)
# 获取全部key
my_dict = {"王昭君": 90, "吉吉国王": 85, "刘禅": 65}
keys = my_dict.keys()
print(f"字典的全部key是:{keys}")
# 遍历字典
# 方式1:通过获取全部key来完成遍历
for key in keys:
print(f"字典的key是:{key}")
print(f"字典的value是:{my_dict[key]}")
# 方式2:直接对字典进行for循环
for key in my_dict:
print(f"字典的key是:{key}")
print(f"字典的value是:{my_dict[key]}")
# 统计字典的元素数量
num = len(my_dict)
print(num)
![](https://i-blog.csdnimg.cn/blog_migrate/f014d2e51088d7d8c4e908c5d3f96f83.png)
# 案例
info_dict = {
"王力宏": {
"部门": "科技部",
"工资": 3000,
"级别": 1
},
"林俊杰": {
"部门": "市场部",
"工资": 7000,
"级别": 3
},
"周杰伦": {
"部门": "市场部",
"工资": 5000,
"级别": 2
},
"张学友": {
"部门": "科技部",
"工资": 4000,
"级别": 1
},
"刘德华": {
"部门": "市场部",
"工资": 6000,
"级别": 2
}
}
for name in info_dict:
if info_dict[name]["级别"] == 1:
employ = info_dict[name]
employ["级别"] = 2 # 级别+1
employ["工资"] += 1000 # 工资+1000
# 将修改的信息更新回info_dict
info_dict[name] = employ # 如:张学友的value赋值为修改后的
print(info_dict)