亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Python多維/嵌套字典數(shù)據(jù)無限遍歷的實(shí)現(xiàn)

原創(chuàng) 2017-01-12 15:07:16 522
摘要:最近拾回Django學(xué)習(xí),實(shí)例練習(xí)中遇到了對(duì)多維字典類型數(shù)據(jù)的遍歷操作問題,Google查詢沒有相關(guān)資料…畢竟是新手,到自己動(dòng)手時(shí)發(fā)現(xiàn)并非想象中簡單,頗有兩次曲折才最終實(shí)現(xiàn)效果,將過程記錄下來希望對(duì)大家有用。實(shí)例數(shù)據(jù)(多重嵌套):person = {"male":{"name":"Shawn"}, "

最近拾回Django學(xué)習(xí),實(shí)例練習(xí)中遇到了對(duì)多維字典類型數(shù)據(jù)的遍歷操作問題,Google查詢沒有相關(guān)資料…畢竟是新手,到自己動(dòng)手時(shí)發(fā)現(xiàn)并非想象中簡單,頗有兩次曲折才最終實(shí)現(xiàn)效果,將過程記錄下來希望對(duì)大家有用。

實(shí)例數(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及對(duì)應(yīng)value循環(huán)檢查該數(shù)據(jù)的每一個(gè)子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)用實(shí)現(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ù)無限遍歷的實(shí)現(xiàn)請(qǐng)關(guān)注PHP中文網(wǎng)(ipnx.cn)其他文章!   


發(fā)佈手記

熱門詞條