Requirements:
Lists the dictionary corresponding node name, according to user input can add nodes, view nodes and other functions, where the address province-city-county as an alternative, this problem familiar with the dictionary nesting function
Vim day13-16.py
db = {}path = []while True: #定义临时字典temp temp = db #path默认是空列表根据进入的节点深度有对应的内容 for item in path: temp = Temp[item] #列出节点下面对应的可选key值 print (' currently selectable node ', List (Temp.keys ()), ' \ n ') choice = input (' 1: Add node; 2: View and enter node ( Q Exit/Return to upper level B) \n>>> ') if choice = = ' 1 ': k = input (' Please enter the name of the child node to be added: ') if k in temp: print (' node already exists ') else: temp[k] = {} elif choice = = ' 2 ': k = input (' Please enter the child node to view: ') if k in temp: Path.append (k) else: print (' child node name error ') elif choice.lower () = = ' B ': If Path: Path.pop () elif choice.lower () = = ' Q ': Break Else: print (' Input not valid ') print (' Dictionary and Path value: ', Db,path)
Perform steps
One, the first cycle of the db is empty so the current optional node output is also empty
Two, input 1 add a node Jiangxi corresponds to a db value of {' Jiangxi ': {}} path or empty
Similarly, add a second node below the same level. Beijing
Three, input 2 into the first node Jiangxi, the DB value has not changed but the path value has been added to the Append method adds a record as ["Jiangxi"], because path has a value using the statement for item in path: Then the dictionary value corresponding to the first level directory {} Assigned to temp so the currently optional node is empty
Four, continue to add two nodes in the first node of Jiangxi Province, respectively, Jian and Nanchang, at this time modified the corresponding temp,temp is the dictionary db["Jiangxi") so the value of the DB will also correspond to change
Five, continue to enter the next level of the node Jian, the value of path into a [' Jiangxi ', ' ji '],for loop executed two times, the first temp=["Jiangxi"]={' Nanchang ': {}, ' Jian ': {}} The second time temp=["Jiangxi" ["Jian"]={} Therefore, the optional node of the current node is empty, in the same vein can continue to add Taihe and other next level node
Six, enter B exits this layer node, because the last element of the list of pop deletions is executed, so the path becomes ["Jiangxi"] again, the same way you enter the second time B and then the pop again back to the first level node
Seven, enter Q to exit the loop directly
In theory, an infinite dictionary nested dictionary can be implemented by this method of dictionary nesting.
Python Full stack day13 (Job instruction dictionary nested implementation user input add and view)