Python用字典构建多级菜单
#key-value
#字典是无序的,因为他没有下标,通过key找
info={
'stu01':"liuhaolai",
'stu02':"wangshulin"
}
print(info['stu01'])
info['stu03']='刘**'#若不存在该key,则直接添加
info['stu04']='王##'
print(info)
#del
del info['stu03']
print(info)
#pop
info.pop('stu04')
print(info)
print(info.get('stu03'))#不确定字典里有没有时用
print('stu01' in info)#判断有没有
print(info.values())#打印值
print(info.keys())#打印key
#字典的嵌套
place={
'辽宁':{
'大连':['很漂亮','很干净'],
'沈阳':['很大','有些乱'],
'阜新':['很小','很安逸']
},
'江苏':{
'南京':['省会','性价比极低'],
'苏州':['古今结合','小桥流水'],
'镇江':['有些乱','一般般']
}
}
print("------")
print(place)
place['江苏']['镇江'][1]='一般般啦'
print(place)
print(place.values())#打印值
print(place.keys())#打印key
place.setdefault('河北',{'唐山:[0,1]'})#查,没有就添加,和get不同
print(place)
print(place.setdefault('江苏',{'苏州:[0,1]'}))#查,没有就添加
info={
'stu01':"liuhaolai",
'stu02':"wangshulin",
'stu03':'lucky',
'stu04':'pangpang'
}
new={
'stu01':'david',
'stu02':'tree',
'stu05':'lala'
}
new.setdefault('stu03','david')#查,没有就添加
print(new)
info.update(new)#将已有的覆盖更新,没有的创建
print(info)
print(info.items())#字典转成列表
c=dict.fromkeys([6,7,8],[1,{"name":'number'}])#初始化一个新字典
print(c)
#字典的循环
info2={
'stu01':"liuhaolai",
'stu02':"wangshulin",
'stu03':'lucky',
'stu04':'pangpang'
}
print(info2.get('stu01'))
print(info2.setdefault('stu01'))
for i in info2:#推荐!!!!!!
print(i,info[i])
print("------")
for k,v in info2.items():#效果一样,但低效
print(k,v)
正文:
需求:
1.三级菜单
2.可依次选择进入各子菜单
3.按b逐级返回,按q退出
# Author:David Liu
# Be Happy!
place={
'辽宁1':{
'大连':{
'甘井子区':['大连理工大学'],
'沙河口区':['数码广场']
},
},
'辽宁2':{
'沈阳': {
'皇姑区': ['辽宁大学'],
'铁西区': ['小树林']
},
},
'辽宁3':{
'阜新': {
'海州区':['胖胖来'],
'细河区':['细河区人民政府']
}
}
}
exit_flag=True
while exit_flag:
for i in place:
print(i)
choice=input("选择进入,按q退出>>")
if choice in place:
while exit_flag:
for i2 in place[choice]:
print('\t',i2)
choice2=input("选择进入,按b返回,按q退出>>")
if choice2 in place[choice]:
while exit_flag:
for i3 in place[choice][choice2]:
print('\t\t', i3)
choice3 = input("选择进入,按b返回,按q退出>>")
if choice3 in place[choice][choice2]:
for i4 in place[choice][choice2][choice3]:
print('\t\t\t',i4)
choice4 = input("最后一层,按b返回,按q退出>>")
if choice4=='b':
pass#没用,占位的
elif choice4=='q':
exit_flag = False
if choice3 == 'b':
break
elif choice3 == 'q':
exit_flag = False
if choice2 == 'b':
break
elif choice2 == 'q':
exit_flag = False
elif choice == 'q':
exit_flag = False
print('\n',"已退出!".center(50,'-'))
标签:info,菜单,stu01,Python,choice,place,print,exit,字典
From: https://www.cnblogs.com/mengdie1978/p/17483063.html