the MENU = { ' Beijing ' : { ' Haidian ' : { ' Wudaokou ' : { ' SOHO ' : {}, ' NetEase ' : {}, ' Google ' : {}}, ' Zhongguancun ' : { ' iQIYI ' : {}, ' car home ' : {}, ' excellent cool " : {} } } }, ' Shanghai ' : {}, ' Guangdong ' : { ' Guangzhou ' : { ' clouds ' : { ' Baiyun Mountain ' : {}, ' Guangdong University of Foreign Studies ' : {} }, ' Panyu ' : { ' Guangzhou University City ' : { ' Guangdong University of Technology ' : { ' second canteen ' : { ' grilled chicken with rice ' }, ' East thirteen before ' : { ' a couple of Poe ' } }, ' South China University of Technology ' : {}, ' Sun Yat-sen ' : {} } } }, ' Chaoshan ' : { ' jieyang ' : { ' jieyang Teachers University ' : {}, ' jieyang INSTITUTE (construction) " : {}, }, ' Shantou ' : { ' STU ' : {} } } } }
Recursive method:
def tri_menu(dic): while True: for k in dic: print(k) key = input('请输入地址:').strip() if key == 'b' or key == 'q': return key elif key in dic.keys() and dic[key]: ret = tri_menu(dic[key]) if ret == 'q': return 'q' tri_menu(menu)
Stack method:
li = [menu] while li: for key in li[-1]: print(key) K = INPUT ( ' Enter location: ' ) .strip () IF K in Li [-1] .keys () and Li [-1 ] [K]: Li.append (Li [ -1 ] [K]) Elif K == ' . b ' : li.pop () elif k == 'q': break else: continue