黑马程序员2022版Python教程学习笔记——数据容器(dict)

1.字典的定义 

字典的定义,同样使用{},不过存储的元素一个个的:键值对

#定义字典字面量
{key: value, key: value,.......,key: value}
#定义字典变量
my_dict = {key: value, key: value,.......,key: value}
#定义空字典
my_dict = {}      #空字典定义方式1
my_dict = dict()  #空字典定义方式2
  • 字典的key不可以重复使用

2.字典数据的获取

字典同集合一样,不可以使用下标索引,但是字典可以通过key值来取得对应的Value

my_dict = {"王":99,"周":88,"林":77}
print(my_dict["周"])
print(my_dict["林"])
print(my_dict["王"])

   

 3.定义嵌套字典

字典的key和value可以是任意数据类型(key不可为字典

stu_score_dict_ = {
    "王":{"语文":77,"数学":66,"英语":33},
    "周":{"语文":88,"数学":86,"英语":55},
    "林":{"语文":88,"数学":86,"英语":55}
}
print(stu_score_dict_)
  •  这个题的里面Value是字典,相当于字典里面又嵌套了一个字典

 4.从嵌套的字典中获取数据

stu_score_dict_ = {
    "王":{"语文":77,"数学":66,"英语":33},
    "周":{"语文":88,"数学":86,"英语":55},
    "林":{"语文":88,"数学":86,"英语":55}
}

score = stu_score_dict_["周"]["语文"]
print(score)

   

5.修改字典

1.新增元素

语法:字典[key] = Value,结果:字典被修改,新增了元素

my_dict = {"王":99,"周":88,"林":77}
my_dict["张"] = 66
print(my_dict)

   

 2.更新元素

语法:字典[key] = Value ,结果是:字典被修改,元素被更新

注意:字典key不可以重复,所以对已存在的key执行上述操作,就是更新value值

my_dict = {"王":99,"周":88,"林":77}
my_dict["王"] = 66
print(my_dict)

   

 3.删除元素

语法:字典.pop(key),结果是:获得指定key的value,同时字典被修改,指定key的数据被删除

my_dict = {"王":99,"周":88,"林":77}
my_dict.pop("王")
print(my_dict)

  

 4.清空字典

语法:字典.clear()结果是:字典被修改,元素被清空

my_dict = {"王":99,"周":88,"林":77}
my_dict.clear()
print(my_dict)

   

 5.获取全部的key

语法:字典.keys(),结果是:得到字典中的全部key

my_dict = {"王":99,"周":88,"林":77}
keys = my_dict.keys()
print(keys)

   

 6.遍历字典

方式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]}")

   黑马程序员2022版Python教程学习笔记——数据容器(dict)_第1张图片

 方式2:直接对字典进行for循环,每一次循环都是直接得到key

for key in my_dict:
     print(f"2字典的key是:{key}")
     print(f"2字典的value是:{my_dict[key]}")

   黑马程序员2022版Python教程学习笔记——数据容器(dict)_第2张图片

 字典不可以使用while循环!!!

7.统计字典内的元素数量

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)

​​​​​​​

你可能感兴趣的:(初阶python学习,学习)