Python实现三级菜单(字典和列表的使用)

menu = {
'北京': {
'海淀': {
'五道口': {
'soho': {},
'网易': {},
'google': {}
},
'中关村': {
'爱奇艺': {},
'汽车之家': {},
'优酷': {}
},
'上地': {
'百度': {}
}

},
'昌平': {
'沙河': {
'老男孩': {},
'北航': {}
},
'天通苑': {},
'回龙观': {}
},
'朝阳': {},
'东城': {}
},

'上海': {
'闵行': {
'人民广场': {
'炸鸡店': {}
}
},
'闸北': {
'火车站': {
'携程': {}
}
},
'浦东': {}
},

'山东': {}
}

current_menu = menu
path_menu = []

while True:
print("菜单(menu)".center(15, '-'))
# 将菜单字典关键字转化为列表类型,便于给菜单加上数字编号,方便用户输入
current_key_list = list(current_menu.keys())
for index, i in enumerate(current_key_list):
print("%s. %s".center(15) % (index, i))
# 对用户输入字符进行校验和容错处理(意外输入空格或回车不报错)
user_choice = input("请输入菜单编号,返回按b,退出按q:").strip()
if user_choice.isdigit() and 0 <= int(user_choice) < len(current_key_list):
# 根据用户输入编号反向查询字典的关键字
current_key = current_key_list[int(user_choice)]
if current_key in current_menu:
# 根据用户进入的菜单层级,保存历史菜单路径并进行下一层菜单的循环打印
path_menu.append(current_menu)
current_menu = current_menu[current_key]
elif user_choice.casefold() == 'b':
if current_menu != menu:
current_menu = path_menu.pop()
else:
print("----已经回到主菜单----!")
elif user_choice.casefold() == 'q':
exit()
posted @ 2018-11-20 22:19  长江南京眼  阅读(630)  评论(0编辑  收藏  举报