手机
当前位置:查字典教程网 >脚本专栏 >python >Python多维/嵌套字典数据无限遍历的实现
Python多维/嵌套字典数据无限遍历的实现
摘要:最近拾回Django学习,实例练习中遇到了对多维字典类型数据的遍历操作问题,Google查询没有相关资料…毕竟是新手,到自己动手时发现并非想...

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

实例数据(多重嵌套):

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是否符合字典特征,如果符合则迭代执行,不符合则返回循环继续执行至结束

具体代码:

def is_dict(dict_a): #此方法弃用,python已提供数据类型检测方法isinstance() try: dict_a.keys() except Exception , data: return False return True def list_all_dict(dict_a): if isinstance(dict_a,dict) : #使用isinstance检测数据类型 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) #自我调用实现无限遍历

结果:

执行 list_all_dict(person),系统回应 :

male : {'name': 'Shawn'} name : Shawn children : {'age': 4, 'name': {'first_name': 'xc0xee', 'last_name': {'now':'xc3xfa', 'old': 'xc3xf7xc3xf7'}}} age : 4 name : {'first_name': 'xc0xee', 'last_name': {'now': 'xc3xfa', 'old':'xc3xf7xc3xf7'}} first_name : 李 last_name : {'now': 'xc3xfa', 'old': 'xc3xf7xc3xf7'} now : 铭 old : 明明 female : {'age': 23, 'name': 'Betty'} age : 23 name : Betty

以上这篇Python多维/嵌套字典数据无限遍历的实现就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持查字典教程网。

【Python多维/嵌套字典数据无限遍历的实现】相关文章:

Python字符遍历的艺术

python两种遍历字典(dict)的方法比较

Python写的Socks5协议代理服务器

python选择排序算法的实现代码

python判断端口是否打开的实现代码

Python使用PyGreSQL操作PostgreSQL数据库教程

python二叉树遍历的实现方法

Python字符转换

wxpython 最小化到托盘与欢迎图片的实现方法

Python时间戳与时间字符串互相转换实例代码

精品推荐
分类导航