字典深层递归遍历之叶子元素换值
材料:复杂(多维度)字典组成的JsonA内有N个叶子元素(叶子结点),现有一维列表ListA(元素以字典形式展现)
任务:遍历ListA中元素属性名是否在JsonA的叶子结点有相同属性名?如果有,则用ListA中元素的值替换掉JsonA中同名元素的值;如果没有,不影响最终结果。直到ListA所有元素遍历完成。
代码:
1 import copy 2 from collections import defaultdict 3 dicta ={ 4 "H": { 5 "ACID": "999", 6 "Ver": ["5.0.0_1.0","5.0.0"], 7 "IMEI": [100,2,1000], 8 "TID": "df22839322dfceb0622b5c6be5879ed852d594d5" 9 }, 10 "B": { 11 "Login": { 12 "Type": "LP","Name": "15806666690","IMEI": "111111","ForToken": 1 13 }, 14 "IMEI": { 15 "IMSI": "460029636249253", 16 "IMEI": "868349029037662", 17 "AndroidID": "ed93e839f67279df", 18 "Mac": "68: 3e: 34: 14: 61: e7", 19 "NetType": "Wifi", 20 "Model": "m2note", 21 "OsVer": "5.1", 22 "AppVer": "4.0.0" 23 } 24 } 25 } 26 27 dictd={'ACID': 'tttttttttttttt', 'Ver': ['8.8.8.8.', '8.8.808888'],'TID': 'HELLO WORLD','ccc':'dddd'} 28 29 def quantizeJsonTemplet(targetDict,sourceList_dict): 30 copytargetDict = copy.deepcopy(targetDict) 31 def recursionReplace(copytargetDict,serchKey,newValue): 32 for k,v in copytargetDict.items(): 33 if isinstance(v,dict) : #值是字典元素,则递归处理 34 recursionReplace(v,serchKey,newValue) 35 else: 36 if k == serchKey: 37 # print ('-----Find it:',k) 38 copytargetDict[k] = newValue #对目标字典元素的值重写 39 return copytargetDict 40 41 for k,v in dictd.items(): 42 recursionReplace(copytargetDict,k,v) 43 return targetDict,copytargetDict 44 result = quantizeJsonTemplet(dicta,dictd) 45 print (result[0],'\n\n',result[1])
输出结果:
{'H': {'ACID': '999', 'Ver': ['5.0.0_1.0', '5.0.0'], 'IMEI': [100, 2, 1000], 'TID': 'df22839322dfceb0622b5c6be5879ed852d594d5'}, 'B': {'Login': {'Type': 'LP', 'Name': '15801570690', 'IMEI': '111111', 'ForToken': 1}, 'IMEI': {'IMSI': '460029636249253', 'IMEI': '868349029037662', 'AndroidID': 'ed93e839f67279df', 'Mac': '68: 3e: 34: 14: 61: e7', 'NetType': 'Wifi', 'Model': 'm2note', 'OsVer': '5.1', 'AppVer': '4.0.0'}}} {'H': {'ACID': 'tttttttttttttt', 'Ver': ['8.8.8.8.', '8.8.808888'], 'IMEI': [100, 2, 1000], 'TID': 'HELLO WORLD'}, 'B': {'Login': {'Type': 'LP', 'Name': '15801570690', 'IMEI': '111111', 'ForToken': 1}, 'IMEI': {'IMSI': '460029636249253', 'IMEI': '868349029037662', 'AndroidID': 'ed93e839f67279df', 'Mac': '68: 3e: 34: 14: 61: e7', 'NetType': 'Wifi', 'Model': 'm2note', 'OsVer': '5.1', 'AppVer': '4.0.0'}}} [Finished in 0.1s]