abstract:最近拾回Django學(xué)習(xí),實例練習(xí)中遇到了對多維字典類型數(shù)據(jù)的遍歷操作問題,Google查詢沒有相關(guān)資料…畢竟是新手,到自己動手時發(fā)現(xiàn)并非想象中簡單,頗有兩次曲折才最終實現(xiàn)效果,將過程記錄下來希望對大家有用。實例數(shù)據(jù)(多重嵌套):person = {"male":{"name":"Shawn"}, "
最近拾回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
更多關(guān)于Python多維/嵌套字典數(shù)據(jù)無限遍歷的實現(xiàn)請關(guān)注PHP中文網(wǎng)(ipnx.cn)其他文章!