SoFunction
Updated on 2025-03-02

Python dictionary implements a simple three-level menu (example explanation)

As shown below:

data = {
 "Beijing":{
  "Changping":{"Shahe":["oldboy","test"],"Tiantongyuan":["Link Real Estate","I love my home"]},
  "Chaoyang":{"Wangjing":["Benz","Momo"],"International Trade":["CICC","HP"],"Dongzhimen":["advent","Fei Xin"]},
  "Haidian":{}
 },
 "Shandong":{
  "Texas":{},
  "Qingdao":{},
  "Jinan":{}
 },
 "Guangdong":{
  "Dongguan":{},
  "Changshu":{},
  "Foshan":{}
 }
}
exit_flag = False
while not exit_flag:
 for i in data:
  print(i)
 choice_s = input("Please enter the name of any of the above provinces or municipalities>>>:")
 if choice_s in data:
  while not exit_flag:
   for i in data[choice_s]:
    print("\t",i)
   choice_q = input("Please enter any of the above city names>>>:")
   if choice_q in data[choice_s]:
    while not exit_flag:
     for i in data[choice_s][choice_q]:
      print("\t\t",i)
     choice_j = input("Please enter any of the above street names>>>:")
     if choice_j in data[choice_s][choice_q]:
      for i in data[choice_s][choice_q][choice_j]:
       print("\t\t",i)
      last = input("The last layer, press b to return >>>:")
      if last == "b":
       pass
      elif last == "q":
       exit_flag = True
     if choice_j == "b":
      break
     elif choice_j == "q":
      exit_flag = True
   if choice_q == "b":
    break
   elif choice_q == "q":
    exit_flag = True

Key points:

1. Dictionary hierarchical relationship

2. Break terminates this loop, pass does nothing, just a placeholder

3. Cleverly use exit_flag = False

The above article on the Python dictionary implementation of a simple three-level menu (example explanation) is all the content I share with you. I hope you can give you a reference and I hope you can support me more.