""" 数据容器:dict字典 1.字典的定义【字】:【含义】 key:Value 2.字典的常用操作 # 定义字典字面量 {key:value, key:value,....,key:value} # 定义字典变量 my_dict = {key:value, key:value,....,key:value} # 定义空字典 my_dict = {} # 空字典定义方式 my_dict = dict() # 空字典定义方式2 和集合my_set = set()相似 """ # 字典的基础定义 my_dict = {"王力宏": 99, "谢绮雯": 100, "林俊杰": 88} # 定义空的字典 my_dict2 = {} # set() my_dict3 = dict() print(my_dict) print(my_dict2) print(my_dict3) # my_dict = {"王力宏": 99, "王力宏": 100, "林俊杰": 88} # key不能重复,但value可以 # print(my_dict) # 不能使用下标索引 my_dict = {"王力宏": 99, "谢绮雯": 100, "林俊杰": 88} score = my_dict["王力宏"] print(f"王力宏的考试分数是:{score}") score = my_dict["谢绮雯"] print(f"谢绮雯的考试分数是:{score}") # 字典的嵌套 key不可以为字典 stu_score_dict = { "王力宏": {"语文": 77, "数学": 66, "英语": 33}, "周杰伦": {"语文": 88, "数学": 86, "英语": 55}, "林俊杰": {"语文": 99, "数学": 96, "英语": 66} } print(stu_score_dict) score = stu_score_dict["周杰伦"]["语文"] print(f"周杰伦的语文分数是:{score}") score = stu_score_dict["林俊杰"]["英语"] print(f"林俊杰的英语分数是:{score}") # 字典的常用操作 """ 1.修改 如何在字典中修改,如果key不存在则是证明新增元素 语法:字典[key] = value 如果key重复,则证明更新value值 2.删除 变量 = 字典.pop() """ my_dict = {"王力宏": 99, "周杰伦": 100, "林俊杰": 88} my_dict["张信哲"] = 77 print(f"字典通过新增元素后的结果是:{my_dict}") my_dict["周杰伦"] = 77 print(f"字典通过新增元素后的结果是:{my_dict}") # 删除元素 socre = my_dict.pop("周杰伦") print(f"字典被移除了一个元素,结果是:{my_dict},周杰伦的考试分数是:{score}") # 清空字典,clear my_dict.clear() print(f"字典被清空了,内容是:{my_dict}") # 获取全部汉字的方法 stu_score = { "王力宏": 77, "周杰伦": 88, "林俊杰": 99 } keys = stu_score.keys() print(keys) # 遍历字典 # 通过获取到全部的key来完成遍历 for key in keys: print(f"字典的key是:{key}") print(f"字典的value是:{stu_score[key]}") # 方法2:直接对字典进行for循环,每一次循环都是直接得到key for key in stu_score: print(f"字典的key是:{key}") print(f"字典的value是:{stu_score[key]}") # 统计字典内的元素数量 num = len(stu_score) print(f"字典中的元素数量有:{num}个")
info_dict = { "王力宏": { "部门": "科技部", "工资": 3000, "级别": 1 }, "周杰伦": { "部门": "市场部", "工资": 5000, "级别": 2 }, "林俊杰": { "部门": "市场部", "工资": 7000, "级别": 3 }, "张学友": { "部门": "科技部", "工资": 4000, "级别": 1 }, "刘德华": { "部门": "市场部", "工资": 6000, "级别": 2 } } print(f"升值加薪之前的结果:{info_dict}") for name in info_dict: # if条件判断符合条件员工 if info_dict[name]["级别"] == 1: info_dict[name]["级别"] = 2 info_dict[name]["工资"] += 1000 print(f"升级加薪之后的结果:{info_dict}")