@myles
2018-04-23T08:49:10.000000Z
字数 1117
阅读 657
老男孩基础
在此输入正文
if __name__ == '__main__':
current_dict = dic
parent_lst = [] #将父级key值放入到列表中
flags = False #设置标志位
while not flags:
for key in current_dict:
print(key)
choose = str(raw_input("请选择,输入b返回上一级菜单,输入q退出菜单:")).strip()
if choose in current_dict:
# parent_lst.append(current_dict) #将当前的状态放入列表中
current_dict = current_dict[choose]
elif choose == 'b':
if parent_lst:
current_dict = parent_lst.pop() # 什么内容被删除了
elif choose == 'q':
flags = True
else:
print("\033[34;1m输入有误,请重新输入\033[0m")
# 第一层字典读取
for key in new_dic:
print(key)
# 第二层字典读取
user_choice_key = input("输入二层字典索引:")
for key in new_dic[user_choice_key]:
print(key)
# 第三层字典读取
user_choice_key = input(输入三层字典索引:)
for key in new_dic[北京][user_choice_key]:
print(key)
以上字典内容的逐层读取,有么有什么特点呢?
第1个特点:都是使用for循环来遍历字典中的key值;
第2个点的:就是每次遍历的字典内容(dic)一直在变,每一层字典的选择都是通过用户输入的来确定遍历的字典对象的;
所以归纳以上2个特点,我可以想到;
这个数据结构,我们可以通过一个for循环配合不断变化的字典列表来实现不同级别数据的读取,即归纳为:
(1) for 循环遍历
(2) 不断变化的字典
# 遍历一节菜单key值
for key in new_dic:
print(key)
# 用户菜单选择
user_choice_key = input("用户菜单选择输入:")
# 根据将用户输入一级菜单(二级数据的key)赋值生成新的二级菜单数据字典。
new_dic = new_dic[user_choice_key] # 取出value(二层数据字典)复制个新字典new_dic
菜单的逐层退出可以通过一个空列表[]
+append()+pop()方法来实现;
lst = []
lst.append() 存储新查询的内容;
lst.pop() 删除最近新查询而增加的列表元素内容;