Python Constructing Multi level Menu Function with Dictionary

  • 2021-07-13 05:52:35
  • OfStack

Related knowledge points:


#key-value
# The dictionary is unordered because it has no subscript and passes through key Looking for 
info={
 'stu01':"liuhaolai",
 'stu02':"wangshulin"
}
print(info['stu01'])
info['stu03']=' Liu **'# If this does not exist key Is added directly 
info['stu04']=' Wang ##'
print(info)
#del
del info['stu03']
print(info)
#pop
info.pop('stu04')
print(info)
print(info.get('stu03'))# I'm not sure if there is any time in the dictionary 
print('stu01' in info)# Judge whether there is 
print(info.values())# Print value 
print(info.keys())# Print key
# Nesting of dictionaries 
place={
 ' Liaoning ':{
  ' Dalian ':[' It's beautiful ',' Very clean '],
  ' Shenyang ':[' Very large ',' Some mess '],
  ' Fuxin ':[' Very small ',' Very comfortable ']
 },
 ' Jiangsu ':{
  ' Nanjing ':[' Provincial capitals ',' Extremely low cost performance '],
  ' Suzhou ':[' Combination of ancient and modern times ',' Small bridge flowing water '],
  ' Zhenjiang ':[' Some mess ','1 Be like ']
 }
}
print("------")
print(place)
place[' Jiangsu '][' Zhenjiang '][1]='1 So-so '
print(place)
print(place.values())# Print value 
print(place.keys())# Print key
place.setdefault(' Hebei ',{' Tangshan :[0,1]'})# Check, add if you don't, and get Different 
print(place)
print(place.setdefault(' Jiangsu ',{' Suzhou :[0,1]'}))# Check, add if you don't have it 
info={
 'stu01':"liuhaolai",
 'stu02':"wangshulin",
 'stu03':'lucky',
 'stu04':'pangpang'
}
new={
 'stu01':'david',
 'stu02':'tree',
 'stu05':'lala'
}
new.setdefault('stu03','david')# Check, add if you don't have it 
print(new)
info.update(new)# Update existing overrides, create none 
print(info)
print(info.items())# Turn dictionary into list 
c=dict.fromkeys([6,7,8],[1,{"name":'number'}])# Initialization 1 A new dictionary 
print(c)
# Loop of dictionary 
info2={
 'stu01':"liuhaolai",
 'stu02':"wangshulin",
 'stu03':'lucky',
 'stu04':'pangpang'
}
print(info2.get('stu01'))
print(info2.setdefault('stu01'))
for i in info2:# Recommend! ! ! ! ! ! 
 print(i,info[i])
print("------")
for k,v in info2.items():# Effect 1 Sample, but inefficient 
 print(k,v)

--------------------------------------------------------------------------------

Text:

Requirements:

Level 1.3 menu
2. You can choose to enter each submenu in turn
3. Press b to return step by step, and press q to exit


# Author : David Liu 
# Be Happy!

place={
 ' Liaoning 1':{
  ' Dalian ':{
   ' Ganjingzi district ':[' Dalian University of Technology '],
   ' Shahekou District ':[' Digital Plaza ']
  },
 },
 ' Liaoning 2':{
  ' Shenyang ': {
   ' Huanggu District ': [' Liaoning University '],
   ' Tiexi District ': [' Grove ']
  },
 },
 ' Liaoning 3':{
  ' Fuxin ': {
   ' Haizhou District ':[' To be fat '],
   ' Xihe district ':[' Xihe District People's government ']
  }
 }
}
exit_flag=True
while exit_flag:
 for i in place:
  print(i)
 choice=input(" Select Enter, press q Quit >>")
 if choice in place:
  while exit_flag:
   for i2 in place[choice]:
    print('\t',i2)
   choice2=input(" Select Enter, press b Back, press q Quit >>")
   if choice2 in place[choice]:
    while exit_flag:
     for i3 in place[choice][choice2]:
      print('\t\t', i3)
     choice3 = input(" Select Enter, press b Back, press q Quit >>")
     if choice3 in place[choice][choice2]:
      for i4 in place[choice][choice2][choice3]:
       print('\t\t\t',i4)
      choice4 = input(" Finally 1 Layer, press b Back, press q Quit >>")
      if choice4=='b':
       pass# Useless, occupying 
      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'," Has quit! ".center(50,'-'))

ps: Let's take a look at the Python dictionary implementation level 3 menu


################################################
# Task Name: 3级菜单              #
# Description:打印省、市、县3级菜单       #
#       可返回上1级           #
#        可随时退出程序          #
#----------------------------------------------#
# Author:Oliver Lee              #
################################################
zone = {
  '山东' : {
    '青岛' : ['4方','黄岛','崂山','李沧','城阳'],
    '济南' : ['历城','槐荫','高新','长青','章丘'],
    '烟台' : ['龙口','莱山','牟平','蓬莱','招远']
  },
  '江苏' : {
    '苏州' : ['沧浪','相城','平江','吴中','昆山'],
    '南京' : ['白下','秦淮','浦口','栖霞','江宁'],
    '无锡' : ['崇安','南长','北塘','锡山','江阴']
  },
  '浙江' : {
    '杭州' : ['西湖','江干','下城','上城','滨江'],
    '宁波' : ['海曙','江东','江北','镇海','余姚'],
    '温州' : ['鹿城','龙湾','乐清','瑞安','永嘉']
  },
  '安徽' : {
    '合肥' : ['蜀山','庐阳','包河','经开','新站'],
    '芜湖' : ['镜湖','鸠江','无为','3山','南陵'],
    '蚌埠' : ['蚌山','龙子湖','淮上','怀远','固镇']
  },
  '广东' : {
    '深圳' : ['罗湖','福田','南山','宝安','布吉'],
    '广州' : ['天河','珠海','越秀','白云','黄埔'],
    '东莞' : ['莞城','长安','虎门','万江','大朗']
  }
}
province_list = list(zone.keys())       #省列表
# flag = False
# flag1 = False
while True:
  print(" 省 ".center(50,'*'))
  for i in province_list:
    print(province_list.index(i)+1,i)    #打印省列表
  pro_id = input("请输入省编号,或输入q(quit)退出:")  #省ID
  if pro_id.isdigit():
    pro_id = int(pro_id)
    if pro_id > 0 and pro_id <= len(province_list):
      pro_name = province_list[pro_id-1]   #根据省ID获取省名称
      city_list = list(zone[pro_name].keys())  #根据省名称获取对应的值,从新字典中获取key,即市列表
      while True:
        print(" 市 ".center(50,'*'))
        for v in city_list:
          print(city_list.index(v)+1,v)    #打印市列表
        city_id = input("请输入市编号,或输入b(back)返回上级菜单,或输入q(quit)退出:")
        if city_id.isdigit():
          city_id = int(city_id)
          if city_id > 0 and city_id <= len(city_list):
            city_name = city_list[city_id-1]  #根据市ID获取市名称
            town_list = zone[pro_name][city_name]  #根据省名称获取对应的值,从新字典中获取值,即县列表
            while True:
              print(" 县 ".center(50,'*'))
              for j in town_list:
                print(town_list.index(j)+1,j)
              back_or_quit = input("输入b(back)返回上级菜单,或输入q(quit)退出:")
              if back_or_quit == 'b':
                break        #终止此层while循环,跳转到上1层While。
              elif back_or_quit == 'q':
                # flag1 = True
                # break        #根据标志位结束程序。
                exit()
              else:
                print("输入非法!")
          else:
            print("编号%d不存在。"%city_id)
        elif city_id == 'b':
          break
        elif city_id == 'q':
          # flag = True
          # break
          exit()
        else:
          print("输入非法!")
        # if flag1:
        #   break
    else:
      print("编号%d不存在。"%pro_id)
  elif pro_id == 'q':
    break
  else:
    print("输入非法!")
  # if flag or flag1:
  #   break

Summarize


Related articles: