Python多維/嵌套字典數(shù)據(jù)無限遍歷的實現(xiàn)
最近拾回Django學習,實例練習中遇到了對多維字典類型數(shù)據(jù)的遍歷操作問題,Google查詢沒有相關資料…畢竟是新手,到自己動手時發(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及對應value循環(huán)檢查該數(shù)據(jù)的每一個子value是否符合字典特征,如果符合則迭代執(zhí)行,不符合則返回循環(huán)繼續(xù)執(zhí)行至結束
具體代碼:
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) #自我調用實現(xiàn)無限遍歷
結果:
執(zhí)行 list_all_dict(person),系統(tǒ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)就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
Python創(chuàng)建類的方法及成員訪問的相關知識總結
今天給大家?guī)淼氖顷P于Python基礎的相關知識,文章圍繞著Python類的方法及成員訪問展開,文中有非常詳細的介紹及代碼示例,需要的朋友可以參考下2021-06-06NumPy實現(xiàn)ndarray多維數(shù)組操作
NumPy一個非常重要的作用就是可以進行多維數(shù)組的操作,這篇文章主要介紹了NumPy實現(xiàn)ndarray多維數(shù)組操作,需要的朋友們下面隨著小編來一起學習學習吧2021-05-05python計算書頁碼的統(tǒng)計數(shù)字問題實例
這篇文章主要介紹了python計算書頁碼的統(tǒng)計數(shù)字問題實例,對比2個實例講述了數(shù)字統(tǒng)計的技巧,非常實用,需要的朋友可以參考下2014-09-09