代码
class recurPostDict: """ 递归获取多维嵌套字典所有层级的key和value """ def __init__(self, datas): self.datas = datas def recur_data(self, data, result=""): """多维/嵌套字典数据无限遍历,获取所有key层和value""" # 使用isinstance检测数据类型:字典类型 if isinstance(data, dict): for k, v in data.items(): if result == "": self.recur_data(v, k) else: self.recur_data(v, result+"_%s" % str(k)) # 列表或元组类型 elif isinstance(data, (list, tuple)): for i in range(len(data)): # 自我调用实现无限遍历,多个时后缀字母开头 self.recur_data(data[i], result+"_%s" % public_tools.forward("a", i)) else: # print(result + "=" + str(data)) self.datas[result] = str(data)
运行:
if __name__ == "__main__": dic = {"name": "zhangsan", "address": {"sheng": "beijing", "shiji": "beijing", "shiqu": ["shijingshan", "p"], "qu": {"1dong": "1", "2dong": "2"}}} t = recurPostDict({}) # 传入空字典{},即datas初始值为{} t.recur_data(dic, result="") # 执行过程 print(t.datas) print(t.datas.keys()) print(t.datas.values())
执行结果
public_tools.forward() 字母表循环迭代实现地址:https://www.cnblogs.com/phoenixy/p/17126439.html
标签:__,recur,Python,self,value,json,result,data,datas From: https://www.cnblogs.com/phoenixy/p/17126455.html