最近拾回Django學習,實例練習中遇到了對多維字典類型數據的遍歷操作問題,Google查詢沒有相關資料…畢竟是新手,到自己動手時發現並非想象中簡單,頗有兩次曲折才最終實現效果,將過程記錄下來希望對大家有用。
實例數據(多重嵌套):
1 |
person = {"male":{"name":"Shawn"}, "female":{"name":"Betty","age":23},"children":{"name":{"first_name":"李", "last_name":{"old":"明明","now":"銘"}},"age":4}} |
目的:
遍歷person中所有嵌套字典類型數據,並以 key : value 的方式顯示思路:首先分析數據是否符合字典特征打印該數據的key及對應value循環檢查該數據的每一個子value是否符合字典特征,如果符合則迭代執行,不符合則返回循環繼續執行至結束
具體代碼:
01 |
def is_dict(dict_a): #此方法棄用,python已提供數據類型檢測方法isinstance() |
02 |
try: |
03 |
dict_a.keys() |
04 |
except Exception , data: |
05 |
return False |
06 |
return True |
07 |
08 |
def list_all_dict(dict_a): |
09 |
if isinstance(dict_a,dict) : #使用isinstance檢測數據類型 |
10 |
for x in range(len(dict_a)): |
11 |
temp_key = dict_a.keys()[x] |
12 |
temp_value = dict_a[temp_key] |
13 |
print"%s : %s" %(temp_key,temp_value) |
14 |
list_all_dict(temp_value) #自我調用實現無限遍歷 |
結果:
執行 list_all_dict(person),系統回應 :
01 |
male : {'name': 'Shawn'} |
02 |
name : Shawn |
03 |
children : {'age': 4, 'name': {'first_name': '\xc0\xee', 'last_name': {'now':'\xc3\xfa', 'old': '\xc3\xf7\xc3\xf7'}}} |
04 |
age : 4 |
05 |
name : {'first_name': '\xc0\xee', 'last_name': {'now': '\xc3\xfa', 'old':'\xc3\xf7\xc3\xf7'}} |
06 |
first_name : 李 |
07 |
last_name : {'now': '\xc3\xfa', 'old': '\xc3\xf7\xc3\xf7'} |
08 |
now : 銘 |
09 |
old : 明明 |
10 |
female : {'age': 23, 'name': 'Betty'} |
11 |
age : 23 |
12 |
name : Betty |
