网络编程
位置:首页>> 网络编程>> Python编程>> Python多维/嵌套字典数据无限遍历的实现

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

作者:jingxian  发布时间:2023-07-22 16:48:56 

标签:Python,多维,嵌套,字典,遍历

最近拾回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': '\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
0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com