當前位置:成語大全網 - 新華字典 - python3 如何解析多層嵌套字典,具體內容打開看

python3 如何解析多層嵌套字典,具體內容打開看

# 見 代碼 ,代碼粘貼上不帶格式,按照圖片用tab鍵調整壹下,圖片是核心部分

simple_dict?=?{

'Large_dict'?:?{'middle_dict1'?:?{'small_dict1'?:?1?,

'small_dict2'?:?2},

'middle_dict2'?:?{'small_dict3'?:?3?,

'small_dict4'?:?4,

'small_dict5':{'small_dict10'?:?1?,

'small_dict22'?:?3},

},

}

}

#?需求分析:?從嵌套字典中,找到值為3的?路徑關系

#?簡化模型:從value為3的值?遞歸向上層的?key?,遞歸過程保存當前已經遞歸的路徑和當前層

#?1.找到字典壹***有多少層:

count?=?0

path?=?''#?設置路徑的全局變量

result?=?[]?#?記錄結論

def?get_count(dict_test):

global?count?#?聲明每次遞歸均是改變全局變量

global?path?#?拼接檔期啊妳的路徑

global?result?#?記錄結果

for?i?in?dict_test:

if?type(dict_test[i]).__name__?=='dict'?:

#?如果是字典,則繼續向下展開,即執行遞歸:

if?count?==?0:#?增加判斷?消除第壹個?<-?出現,邏輯問題

path?=?path?+?i

else:

path?=?path?+?'<-'?+?i

count?+=?1?#?記錄層數

get_count(dict_test[i])

else:

try:

#?如果不是字典?則是鍵值對,查詢value值是不是3,當前i包含兩個內容,壹個是key,壹個是value

if?dict_test[i]?==?3:

#?找到了value?=3?的值

result.append(f"路徑是:?%s,在第%d層"?%?(path?+?'<-'?+?i,?count))

except?Exception?as?result:?#?雖然字典限定了寫法,為了增加健壯性?此位置使用try指令,避免類型錯誤

print(result)

continue

if?__name__?==?'__main__':

get_count(simple_dict)?#?執行遞歸函數

[print(str(i?+?1)?+?':'?+?j)?for?i,?j?in?enumerate(result)]?#?打印結果

'''

結果:?

1:路徑是:?Large_dict<-middle_dict1<-middle_dict2<-small_dict3,在第3層

2:路徑是:?Large_dict<-middle_dict1<-middle_dict2<-small_dict5<-small_dict22,在第4層

'''