七、数据容器:dict字典
1.字典的定义
字典的key和value可以是任意数据类型(key不可以是字典)
#字典的嵌套
dictionary = {
"王力宏":{
"语文":77,
"数学":66,
"英语":33},
"周杰伦":{
"语文":88,
"数学":86,
"英语":55},
"林俊杰":{
"语文":99,
"数学":96,
"英语":66}
}
score = dictionary["王力宏"]["语文"]
print(f"王力宏的语文分数是{score}")
2.字典的常用操作
1)新增元素/更新元素:字典[key] = Value
2)删除元素:字典.pop(key)
3)清空字典:字典.clear
4)获取全部的key:字典.keys()
score = dictionary.keys()
print(score)
5)遍历字典:
keys = dictionary.keys()
for key in keys:
print(f"字典的key是:{key}")
方式2:直接对字典进行for循环,每一次循环都是直接得到key
for key in dictionary:
print(f"字典的key是:{key}")
print(f"字典的value是:{dictionary[key]}")
6)统计字典内元素数量:len()
3.字典的总结
4.练习
dir = {"w":{"bumen":"keji","wages":3000,"rank":1},
"z":{"bumen":"shichang","wages":5000,"rank":2},
"l":{"bumen":"shichang","wages":7000,"rank":3},
"z":{"bumen":"keji","wages":4000,"rank":1},
"lde":{"bumen":"shichang","wages":6000,"rank":2}
}
print(dir)
for keys in dir:
if dir[keys]["rank"] == 1:
dir[keys]["rank"] += 1
dir[keys]["wages"] += 1000
print(f"字典的key为{keys}")
print(f"字典的value为{dir[keys]}")