In the most recent write interface test program, you need to query the value of a key in a multi-layered nested dictionary, check to return, not find the return none, the key of the query can be any level of key, such as value itself is a multi-layer dictionary, or key is already a leaf node.
Thought: Using the recursive idea of Python, step-by-step traversal, and finally return the result value
The final product code refers to the blog content:
Http://www.cnblogs.com/hahaweixiaohenqingcheng/archive/2016/11/14/6062961.html#undefined tried multiple times to find the reference code can no longer be further optimized, Can only be copied:
1 #gets the value corresponding to the Objkey in the dictionary, for use in dictionary nesting2 #targetdict: the dictionary to find; Serchkey: The target key to find3 #RET: The return value is transferred to the outside (upper layer) during recursion. The target is located on the first level, then returns several RET4 #default: No matching Serchkey is found, return to defaults none5 defDict_getvalue (targetdict,serchkey,default=None):6 forKvinchTargetdict.items ():7 ifK = =Serchkey:8 returnv9 elifisinstance (v,dict):TenRET =Dict_getvalue (V,serchkey,default) One ifRet is notDefault#ret is not equal to Default=none, indicating that Serchkey is found, and RET returns to the upper level as the return value. A returnret - returnDefault
View Code
Test data, stitched together in the code above.
1 if __name__=='__main__':2Targetdict ={"H": {"Ver": ["AAAA","bbbb"],"ACID": {'KKK':"AAAAA"},"Cinf": [100,2,1000]},3 "B": {"Login": {"Type":"LP","Name":"41ss676","PWD": {'AAA':"123456"},"Fortoken": 1}}}4 Print(Recursionsearch (Targetdict,'Name'))
assemble the above code directly
Before the finished product, tried several writing, can not meet the final requirements, carried out some analysis, is now recorded:
1, find the key can only be leaf node, non-leaf node can not be implemented to find, the code is as follows:
1 defRecursionsearch (Targetdict,serchkey):#Recursive lookup2 forKvinchTargetdict.items ():3 ifIsinstance (v,dict):#value is a dictionary element, the recursive processing4 Recursionsearch (V,serchkey)5 elifK = =Serchkey:6pp=Targetdict[k]7 Print(PP)8 returnPp
just consider the leaf node is the query target.
Results:
Print (Recursionsearch (targetdict, ' KKK ')) see the value of the printed leaf node is exactly what I want to find the value of key= ' KKK ',
Print (Recursionsearch (targetdict, ' Name ')) changes the leaf node inside the second branch, and can also see the printout in the function 41ss676 is what I want.
Should be right, Python output:
41ss676
None
[Finished in 0.2s]
But the result of the hair function is none???
Analysis:
(1). The code can actually reach the leaf node to find the function of the target key name, but ... Try to change your mind.
2, replace if condition, not directly to the leaf node level to begin to find
1 def recursionsearch (targetdict, Serchkey): # recursive lookup 2 for k,v in Targetdict.items (): 3 if< /span> k == Serchkey: 4 return v 5 elif isinstance (v,dict): # value is a dictionary element, recursively handles 6 recursionsearch (v,serchkey)
any level of lookup, but the code is still wrong
Analysis:
(2). The last line of this program only makes recursive calls, but does not return a recursive value, resulting in recursion, it is necessary to return suspended, the result is necessarily none. The return value of a function without return is the None,python rule.
Refer to the 4th edition of the Python Learning Manual, page 531, "functions without Renturn statements"
3, the return value of the recursive call also return
1 defRecursionsearch (Targetdict,serchkey):#Recursive lookup2 forKvinchTargetdict.items ():3 ifK = =Serchkey:4 returnv5 elifIsinstance (v,dict):#value is a dictionary element, the recursive processing6RET =Recursionsearch (V,serchkey)7 returnRet
result of return recursive call
The result: This code can only be recursively passed through the line of the first element, and will end recursively regardless of whether the target value is eventually found or not found.
The direct result of this mindless increase in return is:
(1). The key found in the first value of the first key value pair, and recursive call, the key is also in the first position of the target dictionary, can return the correct value;
such as: key= ' H ', key= ' ACID ', key= ' KKK ' can return the correct value, if key= ' B ', key= ' Cinf ' will only return none
(2). In other words: Only the first pair (K,V) will be used for the For loop
Analysis:
(1). A processing method must be added to allow the program to loop through the for loop and not be confined to the first pair (K,V).
The main thing is to use MO conditions to limit return ret execution, if this return does not execute, then for can continue to loop down
If the RET is none continue the loop, if RET is not none to prove that the target is found, should return RET, after streamlining the statement: if RET is not none: return ret
Forward testing:
Print (Recursionsearch (targetdict, ' H ')) #{' Ver ': [' aaaa ', ' bbbb '], ' ACID ': {' KKK ': ' AAAAA '}, ' Cinf ': [10 0, 2, 1000]}
Print (Recursionsearch (targetdict, ' ACID ')) #{' KKK ': ' AAAAA '}
Print (Recursionsearch (targetdict, ' KKK ')) #aaaaa
Print (Recursionsearch (targetdict, ' Ver ')) #[' aaaa ', ' bbbb ']
Print (Recursionsearch (targetdict, ' B ')) #{' Login ': {' Type ': ' LP ', ' Name ': ' 41ss676 ', ' Pwd ': {' AAA ': ' 12 3456 '}, ' Fortoken ': 1}}
Print (Recursionsearch (targetdict, ' Login ')) #{' Type ': ' LP ', ' Name ': ' 41ss676 ', ' Pwd ': {' aaa ': ' 123456 '}, ' Fo Rtoken ': 1}
Print (Recursionsearch (targetdict, ' Pwd ')) #{' aaa ': ' 123456 '}
Print (Recursionsearch (targetdict, ' aaa ')) #123456
The above can return the value of the correct target key
Reverse test:
Print (Recursionsearch (targetdict, ' aaaaaa ')) #None没有键属性是 ' aaaaaa ', the value of only one key is ' aaaaaa ' and the test function is a key name lookup
Print (Recursionsearch (targetdict, ' B111 ')) #None
All above can be fought back to none
At this point, from the initial level of error procedures, step-by-step to the correct program.
Thank my colleague and I took the trouble to discuss the day, and finally figured out the principle of the correct procedure, but also step by step analysis of the error where the program is wrong, how to improve.
Python recursion in return code trap