字典的定义,同样使用{},不过存储的元素一个个的:键值对
#定义字典字面量
{key: value, key: value,.......,key: value}
#定义字典变量
my_dict = {key: value, key: value,.......,key: value}
#定义空字典
my_dict = {} #空字典定义方式1
my_dict = dict() #空字典定义方式2
字典同集合一样,不可以使用下标索引,但是字典可以通过key值来取得对应的Value
my_dict = {"王":99,"周":88,"林":77}
print(my_dict["周"])
print(my_dict["林"])
print(my_dict["王"])
字典的key和value可以是任意数据类型(key不可为字典)
stu_score_dict_ = {
"王":{"语文":77,"数学":66,"英语":33},
"周":{"语文":88,"数学":86,"英语":55},
"林":{"语文":88,"数学":86,"英语":55}
}
print(stu_score_dict_)
stu_score_dict_ = {
"王":{"语文":77,"数学":66,"英语":33},
"周":{"语文":88,"数学":86,"英语":55},
"林":{"语文":88,"数学":86,"英语":55}
}
score = stu_score_dict_["周"]["语文"]
print(score)
语法:字典[key] = Value,结果:字典被修改,新增了元素
my_dict = {"王":99,"周":88,"林":77}
my_dict["张"] = 66
print(my_dict)
语法:字典[key] = Value ,结果是:字典被修改,元素被更新
注意:字典key不可以重复,所以对已存在的key执行上述操作,就是更新value值
my_dict = {"王":99,"周":88,"林":77}
my_dict["王"] = 66
print(my_dict)
语法:字典.pop(key),结果是:获得指定key的value,同时字典被修改,指定key的数据被删除
my_dict = {"王":99,"周":88,"林":77}
my_dict.pop("王")
print(my_dict)
语法:字典.clear()结果是:字典被修改,元素被清空
my_dict = {"王":99,"周":88,"林":77}
my_dict.clear()
print(my_dict)
语法:字典.keys(),结果是:得到字典中的全部key
my_dict = {"王":99,"周":88,"林":77}
keys = my_dict.keys()
print(keys)
方式1:通过获取全部的key来完成遍历
my_dict = {"王":99,"周":88,"林":77}
keys = my_dict.keys()
for key in keys:
print(f"字典的key是:{key}")
print(f"字典的value是:{my_dict[key]}")
方式2:直接对字典进行for循环,每一次循环都是直接得到key
for key in my_dict:
print(f"2字典的key是:{key}")
print(f"2字典的value是:{my_dict[key]}")
字典不可以使用while循环!!!
num = len(my_dict)
print(num)
my_dict = {"王力宏":{"部门":"科技部","工资":3000,"级别":1},
"周杰伦":{"部门":"市场部","工资":5000,"级别":2},
"林俊杰":{"部门":"市场部","工资":7000,"级别":3},
"张学友":{"部门":"科技部","工资":4000,"级别":1},
"刘德华":{"部门":"市场部","工资":6000,"级别":2}
}
print(my_dict)
for name in my_dict:
if my_dict[name]["级别"] == 1:
my_dict[name]["级别"] = 2
my_dict[name]["工资"] += 1000
print(my_dict)