import json class Get_Dict_All_Keyvalue: """ 递归获取多维嵌套字典所有层级的key和value """ def __init__(self, analysis_dict): #判断类型,如果是str的需要进行loads处理 self.res_dict = {} self.key_name_set = set() #self.key_name_unique = True if isinstance(analysis_dict, dict): self.recur_dict(analysis_dict) if isinstance(analysis_dict, str): self.recur_dict(json.loads(analysis_dict)) def recur_dict(self, ana_dict: dict, key_name=""): """多维/嵌套字典数据无限遍历,获取所有key层和value""" # 使用isinstance检测数据类型:字典类型 if isinstance(ana_dict, dict): for k, v in ana_dict.items(): if key_name == "": self.recur_dict(v, k) else: self.recur_dict(v, key_name+f"_{k}") # 列表或元组类型 elif isinstance(ana_dict, (list, tuple)): if len(ana_dict) == 1: for i in range(len(ana_dict)): # 自我调用实现无限遍历,单个不加修饰 if isinstance(ana_dict[0], dict): self.recur_dict(ana_dict[i], key_name) else: print(key_name + "=" + str(ana_dict)) self.res_dict[key_name] = str(ana_dict) break else: for i in range(len(ana_dict)): #判断下列表的元素是不是还是字典,如果是字典那就继续下钻,否则就是终端值 if isinstance(ana_dict[0], dict): # 自我调用实现无限遍历,多个增加字母修饰 self.recur_dict(ana_dict[i], key_name+f"_{i}") else: print(key_name + "=" + str(ana_dict)) self.res_dict[key_name] = str(ana_dict) break else: print(key_name + "=" + str(ana_dict)) self.res_dict[key_name] = str(ana_dict) last_key_name = key_name.split('_')[-1] if last_key_name not in self.key_name_set: self.key_name_set.add(last_key_name) else: print('重复key', last_key_name) if __name__ == "__main__": test_dic = {"name": "zhangsan", "address": {"sheng": "beijing", "shiji": "beijing", "shiqu": ["shijingshan", "p"], "qu": {"1dong": "1", "2dong": "2"}}} t = Get_Dict_All_Keyvalue(test_dic) # 传入空字典{},即ana_dicts初始值为{} print(t.res_dict) print(t.res_dict.keys()) print(t.res_dict.values())
标签:ana,self,value,json,dict,str,key,name From: https://www.cnblogs.com/hushaojun/p/17594189.html