字典的定义
字典的定义,同样是使用{},不过存储的元素是一个个的键值对
基本语法:
#定义字典字面量
{key:value,key:value,key:value,......key:value}
#定义字典变量
my_dict={key:value,key:value,key:value,......key:value}
#定义空字典
my_dict={}
my_dict=dict()
字典key值重复,后面出现的value值会覆盖前面的value值
无下标索引
字典数据的获取
语法:字典[key] 可以取到对应value值
字典的key可以为任意数据类型,key不能是字典
可嵌套例如
#字典嵌套
my_dict4={"王力宏":{"语文":77,"数学":66,"英语":33},"周杰伦":{"语文":88,"数学":86,"英语":55},"王力宏":{"语文":99,"数学":96,"英语":66}}
score=my_dict4["周杰伦"]["语文"]
print(f"周杰伦的语文成绩:{score}")
新增元素
字典名[key]=value
更新元素
字典名[key]=value
删除元素
语法:字典.pop(key)
结果:获得指定key的value,同时字典被修改,指定key的数据被删除
清空字典
字典.clear()
获取全部key
语法:字典.keys()
遍历字典
for key in keys:
循环体
统计字典元素数量
len(字典)
#定义字典字面量
{"zhangsan":45,"lisi":55,"wangwu":30}
#定义字典变量
my_dict={"zhangsan":45,"lisi":55,"wangwu":30}
#定义空字典
my_dict1={}
my_dict2=dict()
print(f"my_dict的内容是{my_dict},类型是{type(my_dict)}")
print(f"my_dict1的内容是{my_dict1},类型是{type(my_dict1)}")
print(f"my_dict2的内容是{my_dict2},类型是{type(my_dict2)}")
#定义重复key的字典
my_dict3={"zhangsan":45,"zhangsan":35,"lisi":55,"wangwu":30}
print(f"my_dict3的内容是{my_dict3},类型是{type(my_dict2)}")
#字典数据的获取
print(my_dict3["zhangsan"])
print(my_dict3["lisi"])
print("wangwu")
#字典嵌套
my_dict4={"王力宏":{"语文":77,"数学":66,"英语":33},"周杰伦":{"语文":88,"数学":86,"英语":55},"王力宏":{"语文":99,"数学":96,"英语":66}}
score=my_dict4["周杰伦"]["语文"]
print(f"周杰伦的语文成绩:{score}")
#新增元素
my_dict={"zhangsan":45,"lisi":55,"wangwu":30}
my_dict["zhaoliu"]=60
print(my_dict)
#修改元素
my_dict["zhangsan"]=50
print(my_dict)
#删除元素
score=my_dict.pop("lisi")
print(my_dict)
#清空字典
my_dict.clear()
#获取所有key
my_dict={"zhangsan":45,"lisi":55,"wangwu":30}
xcore=my_dict.keys()
print(xcore)
#遍历字典
#通过获取所有key值
for key in xcore:print(f"字典的key值{key}")print(f"字典的value值{my_dict[key]}")
#直接遍历
for key in my_dict:print(f"2字典的key值{key}")print(f"2字典的value值{my_dict[key]}")#统计字典元素
num=len(my_dict)
print(f"my_dict的元素个数{num}")