#字典
#字典的定义,同样是使用{},不过存储的元素是一个个的:键值对。如下语法:
my_dict={"周杰伦":99,"林俊杰":99}
print(f"字典的内容是:{my_dict},类型是:{type(my_dict)}")
#定义重复key的字典,运行后只会显示一个
my_dict={"周杰伦":99,"周杰伦":99}
print(f"重复key的字典的内容是:{my_dict}")
#字典同集合一样,不可以使用下标所引,而是使用key查找
my_dict={"周杰伦":99,"凤凰传奇":99}
score = my_dict["周杰伦"]
print(f"周杰伦的成绩是:{score}")
#字典的嵌套
stu_score_dict = {
"alex":{
"语文":77,
"数学":88,
"英语":99
},
"jane":{
"语文":77,
"数学":88,
"英语":99
},
"jack":{
"语文":77,
"数学":88,
"英语":99
}
}
print(f"学生的成绩信息是:{stu_score_dict}")
#从嵌套字典中获取数据
score = stu_score_dict["jack"]["语文"]
print(f"jack的语文分数是:{score}")
#字典的常规操作
my_dict = {"周杰伦":99,"陈哲远":99}
#新增元素
my_dict["张信哲"] = 99
print(f"字典经过新增元素后,结果为:{my_dict}")
#更新元素
print(f"字典更新前为:{my_dict}")
my_dict["周杰伦"]=100
print(f"字典经过更新元素后,结果为:{my_dict}")
#删除元素,既可以删除又可以得到被删除的值
score = my_dict.pop("周杰伦")
print(f"字典中移除一个元素后为:{my_dict},此刻再来查询这个元素的值为:{score}")
#清空元素
my_dict.clear()
print(f"字典被请清空,内容是{my_dict}")
#获取全部的key
my_dict = {"周杰伦":99,"陈哲远":99}
keys = my_dict.keys()
print(f"字典的全部keys是:{keys}")
#遍历元素
#方式一:通过获取到全部的key来完成遍历
for key in keys:
print(f"字典的key是:{key}")
print(f"字典的value是:{my_dict[key]}")
#方式二:直接对字典进行for循环,每一次循环都是直接得到key
for key in my_dict:
print(f"字典的key是:{key}")
print(f"字典的value是:{my_dict[key]}")
#统计字典内的元素 len()函数
num = len(my_dict)
print(f"字典的元素数量有:{num}个")
#综合练习
people_salary_dict = {
"alex":{
"部门":"科技部",
"工资":3000,
"级别":1
},
"jane":{
"部门":"市场部",
"工资":5000,
"级别":2
},
"jack":{
"部门":"市场部",
"工资":7000,
"级别":3
},
"dack":{
"部门":"科技部",
"工资":4000,
"级别":1
}
}
# print(f"全体员工当前的薪资如下:")
# for key in people_salary_dict:
# print(f"{key}:{people_salary_dict[key]}")
# print(f"全体员工级别为1的员工完成加薪后的薪资如下:")
# for key in people_salary_dict:
# grade = people_salary_dict[key]
# score = grade['级别']
# if score == 1:
# grade['工资'] += 1000
# grade['级别'] += 1
# print(f"{key}:{people_salary_dict[key]}")
print(f"全体员工当前的薪资如下:{people_salary_dict}")
for name in people_salary_dict:
if people_salary_dict[name]["级别"] == 1:
get_dict = people_salary_dict[name]
get_dict["级别"] = 2
get_dict["工资"] += 1000
people_salary_dict[name] = get_dict
print(f"对员工进行加工后:{people_salary_dict}")
五类数据容器的差别对比: