python---字典
2023-01-31 04:01:50
python
#字典是key-value的数据类型,字典是无序的,没有下标(列表有下标),key必须是唯一的
info = {
"stu001":"fengxiaoli",
"stu002":"cx",
"stu003":"wyc",
"stu004":"ljh",
}
###-----------------循环字典
for i in info: #推荐使用
print(i,info[i])
for k,v in info.items(): #不推荐,因为它是先转化为列表在打印,数据量的时候数据会很慢
print(k,v)
###-----------------查询
print("stu001" in info) #判断key是否在字典中,同py2中 info.has_key("stu001")
print(info.get("stu002")) #通过key获取value,推荐使用
print(info["stu001"])
print(info)
###-----------------修改
info["stu003"] = "fzl" #有那个key就修改,没有新增
info["stu005"] = "fzl"
print(info)
###-----------------删除
del info #删除整个字典
del info["stu005"]
info.pop("stu004")
info.popitem() #随机删除一组
###-----------------合并两个字典
b = {
"stu001":"fxl",
3:5,
4:8,
}
info.update(b) #合并字典info和字典b,有重复的就更新,不重复的就合并
print(info)
###-----------------把字典转成列表
print(info.items())
###-----------------初始化一个字典
c = dict.fromkeys([7,8,9],"test")
print(c)
#输出{8: 'test', 9: 'test', 7: 'test'}
c1 = dict.fromkeys([7,8,9],{1:"feng",2:"cx",3:"fxl"})
print(c1)
#输出{8: {1: 'feng', 2: 'cx', 3: 'fxl'}, 9: {1: 'feng', 2: 'cx', 3: 'fxl'}, 7: {1: 'feng', 2: 'cx', 3: 'fxl'}}
c1[8][2]="xia" #类似浅copy,二级字典中数据指向同一内存地址,修改一个所有都改变
print(c1)
#输出{8: {1: 'feng', 2: 'xia', 3: 'fxl'}, 9: {1: 'feng', 2: 'xia', 3: 'fxl'}, 7: {1: 'feng', 2: 'xia', 3: 'fxl'}}
###-----------------多级字典
info2 = {
"stu001":{"fxl":["性别:男","年龄:21"]},
"stu002":{"cx":["性别:女","年龄:25"]},
"stu003":{"fzl":["性别:男","年龄:35"]},
}
info2["stu001"]["fxl"][1] = "年龄:23" #修改
info2.setdefault("stu004",{"ljh":["性别:女","年龄:40"]}) #增加,如果字典中有这个key就不改变原值,没有就新建
print(info2)
三级菜单练习
# Author:fengxiaoli
Data={
"重庆":{
"綦江":{
"永城":["永城中学","永城小学"],
"隆盛":["隆盛中学","隆盛小学"],
"三角":["三角中学","三角小学"],
"丁山":["丁山中学","丁山小学"],
},
"永川":{},
"江北":{},
"沙坪坝":{},
},
"北京":{},
"上海":{},
"天津":{}
}
while True:
for i in Data:
print(i)
choice1=input("1>>>>>")
if choice1 in Data:
while True:
for j in Data[choice1]:
print(j)
choice2 = input("2>>>>>")
if choice2 in Data[choice1]:
while True:
for k in Data[choice1][choice2]:
print(k)
choice3= input("3>>>>>")
if choice3 in Data[choice1][choice2]:
while True:
for t in Data[choice1][choice2][choice3]:
print(t)
choice4= input("最后一层,返回按b:")
if choice4 == "b":
break
elif choice4=="q":
exit()
if choice3 == "b":
break
elif choice3 == "q":
exit()
if choice2 == "b":
break
elif choice2 == "q":
exit()
相关文章