Python多維/嵌套字典數(shù)據(jù)無限遍歷的實現(xiàn)
最近拾回Django學(xué)習(xí),實例練習(xí)中遇到了對多維字典類型數(shù)據(jù)的遍歷操作問題,Google查詢沒有相關(guān)資料…畢竟是新手,到自己動手時發(fā)現(xiàn)并非想象中簡單,頗有兩次曲折才最終實現(xiàn)效果,將過程記錄下來希望對大家有用。
實例數(shù)據(jù)(多重嵌套):
person = {"male":{"name":"Shawn"}, "female":{"name":"Betty","age":23},"children":{"name":{"first_name":"李", "last_name":{"old":"明明","now":"銘"}},"age":4}}
目的:
遍歷person中所有嵌套字典類型數(shù)據(jù),并以 key : value 的方式顯示思路:首先分析數(shù)據(jù)是否符合字典特征打印該數(shù)據(jù)的key及對應(yīng)value循環(huán)檢查該數(shù)據(jù)的每一個子value是否符合字典特征,如果符合則迭代執(zhí)行,不符合則返回循環(huán)繼續(xù)執(zhí)行至結(jié)束
具體代碼:
def is_dict(dict_a): #此方法棄用,python已提供數(shù)據(jù)類型檢測方法isinstance() try: dict_a.keys() except Exception , data: return False return True def list_all_dict(dict_a): if isinstance(dict_a,dict) : #使用isinstance檢測數(shù)據(jù)類型 for x in range(len(dict_a)): temp_key = dict_a.keys()[x] temp_value = dict_a[temp_key] print"%s : %s" %(temp_key,temp_value) list_all_dict(temp_value) #自我調(diào)用實現(xiàn)無限遍歷
結(jié)果:
執(zhí)行 list_all_dict(person),系統(tǒng)回應(yīng) :
male : {'name': 'Shawn'}
name : Shawn
children : {'age': 4, 'name': {'first_name': '\xc0\xee', 'last_name': {'now':'\xc3\xfa', 'old': '\xc3\xf7\xc3\xf7'}}}
age : 4
name : {'first_name': '\xc0\xee', 'last_name': {'now': '\xc3\xfa', 'old':'\xc3\xf7\xc3\xf7'}}
first_name : 李
last_name : {'now': '\xc3\xfa', 'old': '\xc3\xf7\xc3\xf7'}
now : 銘
old : 明明
female : {'age': 23, 'name': 'Betty'}
age : 23
name : Betty
以上這篇Python多維/嵌套字典數(shù)據(jù)無限遍歷的實現(xiàn)就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Python Numpy教程之排序,搜索和計數(shù)詳解
這篇文章主要為大家詳細介紹了Python?NumPy中排序,搜索和計數(shù)的實現(xiàn),文中的示例代碼講解詳細,對我們學(xué)習(xí)Python有一定幫助,需要的可以參考一下2022-08-08
Python集合中remove()函數(shù)的使用方法詳解
這篇文章主要給大家介紹了關(guān)于python集合中remove()函數(shù)的使用,以及在使用Python集合的remove方法時應(yīng)注意的事項,文中通過示例代碼介紹的非常詳細,需要的朋友可以參考下2023-07-07
python os.path.isfile 的使用誤區(qū)詳解
今天小編就為大家分享一篇python os.path.isfile 的使用誤區(qū)詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-11-11
Python3轉(zhuǎn)換html到pdf的不同解決方案
今天小編就為大家分享一篇關(guān)于Python3轉(zhuǎn)換html到pdf的不同解決方案,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧2019-03-03

