Python多维/嵌套字典数据无限遍历

最近拾回Django学习,实例练习中遇到了对多维字典类型数据的遍历操作问题,Google查询没有相关资料…毕竟是新手,到自己动手时发现并非想象中简单,颇有两次曲折才最终实现效果,将过程记录下来希望对大家有用。

实例数据(多重嵌套):

1person = {"male":{"name":"Shawn"}, "female":{"name":"Betty","age":23},"children":{"name":{"first_name":"李""last_name":{"old":"明明","now":"铭"}},"age":4}}

目的:

遍历person中所有嵌套字典类型数据,并以 key : value 的方式显示思路:首先分析数据是否符合字典特征打印该数据的key及对应value循环检查该数据的每一个子value是否符合字典特征,如果符合则迭代执行,不符合则返回循环继续执行至结束

具体代码:

01def is_dict(dict_a): #此方法弃用,python已提供数据类型检测方法isinstance()
02    try:
03        dict_a.keys()
04    except Exception , data:
05        return False
06    return True
07 
08def list_all_dict(dict_a):
09    if isinstance(dict_a,dict) : #使用isinstance检测数据类型
10        for 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),系统回应 :

01male : {'name''Shawn'}
02name : Shawn
03children : {'age'4'name': {'first_name''\xc0\xee''last_name': {'now':'\xc3\xfa''old''\xc3\xf7\xc3\xf7'}}}
04age : 4
05name : {'first_name''\xc0\xee''last_name': {'now''\xc3\xfa''old':'\xc3\xf7\xc3\xf7'}}
06first_name : 李
07last_name : {'now''\xc3\xfa''old''\xc3\xf7\xc3\xf7'}
08now : 铭
09old : 明明
10female : {'age'23'name''Betty'}
11age : 23
12name : Betty
原文地址:https://www.cnblogs.com/lhj588/p/2516046.html