使用 python 遍历出数据库中三级菜单
昨天面试的时候提到了这个问题,但是由于面试时有点紧张,加上之前没做过这个,没写出来,今天补出来。
code
a=[ {"id":1,"menu_name":"菜单1","pid":0}, {"id":2,"menu_name":"菜单1-1","pid":1}, {"id":3,"menu_name":"菜单1-2","pid":1}, {"id":4,"menu_name":"菜单1-3","pid":1}, {"id":5,"menu_name":"菜单1-1-1","pid":2}, {"id":6,"menu_name":"菜单1-1-2","pid":2}, {"id":7,"menu_name":"菜单2","pid":0}, {"id":8,"menu_name":"菜单2-1","pid":7}, {"id":9,"menu_name":"菜单2-2","pid":7}, {"id":10,"menu_name":"菜单2-3","pid":7}, {"id":11,"menu_name":"菜单2-1-1","pid":8}, {"id":12,"menu_name":"菜单2-1-2","pid":8}, {"id":13,"menu_name":"菜单2-2-1","pid":9}, {"id":14,"menu_name":"菜单2-3-1","pid":10}, {"id":15,"menu_name":"菜单2-3-2","pid":10}, {"id":16,"menu_name":"菜单2-3-3","pid":10}, {"id":17,"menu_name":"菜单2-3-4","pid":10} ] def get_menu(a): dic_test={} for tcc in a: if(tcc["pid"]==0): dic_test[tcc["menu_name"]]={"id":tcc["id"],"child":[]} for i in dic_test: index1=dic_test[i]["id"] menu_name1=i for j in a: if(j["pid"]==index1): dic_test[menu_name1]["child"].append({j["menu_name"]:{"id":j["id"],"child":[]}}) if(dic_test[menu_name1]["child"]): for indexc,k in enumerate(dic_test[menu_name1]["child"]): for l in a: for x,b in k.items(): if(b["id"]==l["pid"]): dic_test[menu_name1]["child"][int(indexc)][x]["child"].append({l["menu_name"]:{"id":l["id"],"child":[]}}) return dic_test print(get_menu(a)) #输出 ''' { '菜单1': { 'id': 1, 'child': [{ '菜单1-1': { 'id': 2, 'child': [{ '菜单1-1-1': { 'id': 5, 'child': [] } }, { '菜单1-1-2': { 'id': 6, 'child': [] } }] } }, { '菜单1-2': { 'id': 3, 'child': [] } }, { '菜单1-3': { 'id': 4, 'child': [] } }] }, '菜单2': { 'id': 7, 'child': [{ '菜单2-1': { 'id': 8, 'child': [{ '菜单2-1-1': { 'id': 11, 'child': [] } }, { '菜单2-1-2': { 'id': 12, 'child': [] } }] } }, { '菜单2-2': { 'id': 9, 'child': [{ '菜单2-2-1': { 'id': 13, 'child': [] } }] } }, { '菜单2-3': { 'id': 10, 'child': [{ '菜单2-3-1': { 'id': 14, 'child': [] } }, { '菜单2-3-2': { 'id': 15, 'child': [] } }, { '菜单2-3-3': { 'id': 16, 'child': [] } }, { '菜单2-3-4': { 'id': 17, 'child': [] } }] } }] } } '''