python dist的使用
创建一个dicts
dicts={"name":"张三","age":18,"xb":"男"};
#取值
print(dicts["name"])
#修改值
dicts["name"]="李四"
print(dicts)
#新增
dicts["set"]="nv"
print(dicts)
#删除
dicts.pop("set")
print(dicts);
#判断健是否存在
print("set" in dicts);
# 定义空字典
my_dict1 = {}
# 从字典中通过key取值
score = my_dict["小红"]
print(f"获取小红分数:{score}")
# 定义嵌套字典
stu_score = {
"小红": {"语文": 77, "数学": 66, "英语": 33},
"小丽": {"语文": 88, "数学": 86, "英语": 55},
"小李": {"语文": 99, "数学": 96, "英语": 66},
}
stu_score1=stu_score["小李"]["语文"]
print(f"获取嵌套字典数据:{stu_score1}")
# 遍历,修改嵌套字典值
for name in stu_score:
# 判断内层成绩等于77分
if stu_score[name]["语文"] == 77:
# 把内层字典取出来
name_dict = stu_score[name]
#操作内层字典元素
name_dict["语文"] += 22
# 把内层字典放回外层字典
stu_score[name] = name_dict
print(f"修改后:{stu_score}")
运行结果
张三
{‘name’: ‘李四’, ‘age’: 18, ‘xb’: ‘男’}
{‘name’: ‘李四’, ‘age’: 18, ‘xb’: ‘男’, ‘set’: ‘nv’}
{‘name’: ‘李四’, ‘age’: 18, ‘xb’: ‘男’}
False
字典{‘小红’: 80, ‘小丽’: 85, ‘小李’: 90}
获取小红分数:80
获取嵌套字典数据:99
修改后:{‘小红’: {‘语文’: 99, ‘数学’: 66, ‘英语’: 33}, ‘小丽’: {‘语文’: 88, ‘数学’: 86, ‘英语’: 55}, ‘小李’: {‘语文’: 99, ‘数学’: 96, ‘英语’: 66}}