1 # 简单吧简单吧,用动态变量不停的改变进行遍历 2 menu = { 3 "北京":{ 4 "朝阳":{ 5 "国贸":{ 6 "CICC":{}, 7 "HP":{}, 8 "CCTV":{}, 9 },10 "望京":{11 "陌陌":{},12 "奔驰":{},13 "360":{},14 },15 "三里屯":{16 "优衣库":{},17 "apple":{},18 }19 },20 "昌平":{21 "沙河":{22 "老男孩":{},23 "阿泰包子":{},24 },25 "天通苑":{26 "链家":{},27 "我爱我家":{},28 },29 "回龙观":{},30 },31 "海淀":{32 "五道口":{33 "谷歌":{},34 "网易":{},35 "Sohu":{},36 "Sogo":{},37 "快手":{},38 },39 "中关村":{40 "youku":{},41 "Iqiyi":{},42 "汽车之家":{},43 "新东方":{},44 "腾讯":{},45 46 },47 },48 },49 "上海":{50 "浦东":{51 "陆家嘴":{52 "CICC":{},53 "高盛":{},54 "摩根":{},55 },56 "外滩":{},57 },58 "闵行":{},59 "静安":{},60 "":{},61 },62 "山东":{63 "济南":{},64 "德州":{65 "乐陵":{66 "顶乌镇":{},67 "城区":{},68 },69 "平原":{},70 },71 "青岛":{},72 },73 }74 75 current_layer = menu #实现动态循环的初始变量76 # parent_layer = menu77 parent_layers = [] #保存父籍,最后一个元素永远都是父亲籍78 while True :79 for key in current_layer:80 print(key)81 choice = input(">>>:").strip()82 if len(choice) == 0:continue83 if choice in current_layer:84 parent_layers.append( current_layer) #在进下一层之前把当前层进行尾部追加,即下一层的父亲籍85 current_layer = current_layer[choice] #将要被遍历的字典范围根据用户输入进行缩减范围86 elif choice == "b":87 if parent_layers:88 current_layer = parent_layers.pop()#进行最后一个的弹出并赋值返回父亲层89 else:90 print("无此项")