Python(17)递归实现获取多维嵌套字典所有层级的key和value

本文介绍了一种使用递归函数处理多维嵌套字典的方法,该方法能够获取所有层级的key和value,并将key的每一层都完整展示出来。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用递归函数,获取多维嵌套字典所有层级的key和value,且key带路径

取深层的value值,并把key值得每一层都显示,例如下文中的测试字典raw_dict的server-addr展示为spring.cloud.nacos.discovery.server-addr': 'nacos.al:8848'

实现代码如下

raw_dict={
	'spring': {
		'cloud': {
			'nacos': {
				'discovery': {
					'server-addr': 'nacos.al:8848'
				}
			}
		},
		'datasource': {
			'url': 'jdbc:mysql://rm-3ns202ceq03dayyg8.mysql.rds.aliyuncs.com:3306/xxx?useUnicode=true&characterEncoding=utf8&useSSL=false',
			'username': 'app',
			'password': '123456'
		}
	},
	'dubbo': {
		'registry': {
			'address': 'nacos://nacos.al:8848'
		}
	},
	'custom-config': {
		'bill-config': {
			'extension-config': {
				'extensionMultiPrepaymentRNVersion': 200,
				'multiCashInstallmentByRNVersion': 502,
				'extensionInstallment2PDL': 200
			},
			'grayscaleNewVersionTagId': 6463
		},
		'credit-config': {
			'cash-loan-config': {
				'blacklist': []
			},
			'cash-installment-config': {
				'blacklist': []
			}
		},
		'financial-page-config': {
			'newVersion4NotLogin': True,
			'newVersion4AllLogin': True,
			'newVersionTailNumberSet': [0, 1, 2, 3, 4, 5, 7, 8, 9]
		},
		'repayment-config': {
			'combinerRepayDisabledTagId': 5905
		},
		'payCenterConfigMap': {
			'afi': {
				'bizCode': 'afiRP',
				'secretKey': '112233445566'
			}
		}
	},
	'asetku': {
		'loan': {
			'host': 'http://test.supermarket'
		}
	},
	'kms': {
		'appId': 'xxx',
		'token': '12f3b4b5-678d-9cec-af12-dc12e34f5ad6'
	}
}


class AnalyzeDataUtil:
    def __init__(self, datas):
        self.datas = datas

    def analyze_data(self, data, result="raw_dict"):
    """多维/嵌套字典数据无限遍历,获取所有key层和value
        :param data:
        :param result:
        :return:
        """
        if isinstance(data, dict): #使用isinstance检测数据类型:字典类型
            for k,v in data.items():
                self.analyze_data(v, result+".%s" %str(k))
        elif isinstance(data,(list, tuple)): #列表或元组类型
            for i in range(len(data)):
                self.analyze_data(data[i], result+"[%s]" %i) # 自我调用实现无限遍历
        else:
            # print(result + "=" + str(data))
            self.datas[result] = str(data)

if __name__ == '__main__':
    t = AnalyzeDataUtil({})  # 传入空字典{},即datas初始值为{}
    t.analyze_data(raw_dict,result="raw_dict")  #执行过程
    print(t.datas) # 最终需要的是类属性datas

返回结果如下

{'raw_dict.spring.cloud.nacos.discovery.server-addr': 'nacos.al:8848', 
'raw_dict.spring.datasource.url': 'jdbc:mysql://rm-3ns202ceq03dayyg8.mysql.rds.aliyuncs.com:3306/personal_service?useUnicode=true&characterEncoding=utf8&useSSL=false', 
'raw_dict.spring.datasource.username': 'app', 
'raw_dict.spring.datasource.password': '123456', 
'raw_dict.dubbo.registry.address': 'nacos://nacos.al:8848', 
'raw_dict.custom-config.bill-config.extension-config.extensionMultiPrepaymentRNVersion': '200', 'raw_dict.custom-config.bill-config.extension-config.multiCashInstallmentByRNVersion': '502', 'raw_dict.custom-config.bill-config.extension-config.extensionInstallment2PDL': '200', 
'raw_dict.custom-config.bill-config.grayscaleNewVersionTagId': '6463', 
'raw_dict.custom-config.financial-page-config.newVersion4NotLogin': 'True', 
'raw_dict.custom-config.financial-page-config.newVersion4AllLogin': 'True', 
'raw_dict.custom-config.financial-page-config.newVersionTailNumberSet[0]': '0', 
'raw_dict.custom-config.financial-page-config.newVersionTailNumberSet[1]': '1', 
'raw_dict.custom-config.financial-page-config.newVersionTailNumberSet[2]': '2', 
'raw_dict.custom-config.financial-page-config.newVersionTailNumberSet[3]': '3', 
'raw_dict.custom-config.financial-page-config.newVersionTailNumberSet[4]': '4', 
'raw_dict.custom-config.financial-page-config.newVersionTailNumberSet[5]': '5', 
'raw_dict.custom-config.financial-page-config.newVersionTailNumberSet[6]': '7', 
'raw_dict.custom-config.financial-page-config.newVersionTailNumberSet[7]': '8', 
'raw_dict.custom-config.financial-page-config.newVersionTailNumberSet[8]': '9', 
'raw_dict.custom-config.repayment-config.combinerRepayDisabledTagId': '5905', 
'raw_dict.custom-config.payCenterConfigMap.afi.bizCode': 'afiRP', 
'raw_dict.custom-config.payCenterConfigMap.afi.secretKey': '112233445566', 
'raw_dict.asetku.loan.host': 'http://test.supermarket', 
'raw_dict.kms.appId': 'xxx', 
'raw_dict.kms.token': '12f3b4b5-678d-9cec-af12-dc12e34f5ad6'}
### 使用Python实现类似PyCharm的树状目录结构 为了创建类似于 PyCharm IDE 中显示的文件目录树形结构,可以利用 Python 的 `os` `json` 库来遍历指定路径并构建相应的层次结构。下面是一个简单的例子,该方法会递归地访问每一个子目录,并将其内容整理成易于阅读的形式。 #### 构建函数以获取目录结构 ```python import os from collections import defaultdict def get_directory_structure(rootdir): """ 获取给定根目录下的所有文件夹及其内部文件列表, 并返回一个字典表示这种关系。 参数: rootdir (str): 起始查找位置 返回值: dict: 文件夹名映射至其内含项名称组成的集合 """ dir_tree = {} for base, dirs, files in os.walk(rootdir): folder_name = os.path.basename(base) items = set(files + dirs) # 建立当前层级的关系表 current_level = {folder_name: list(items)} # 将每一层级的信息加入总的结果集中 parent_dir = os.path.dirname(base).replace(rootdir, '').strip(os.sep) nested_dict = dir_tree if parent_dir != '': path_parts = parent_dir.split(os.sep) for part in path_parts[:-1]: nested_dict = nested_dict.setdefault(part, {}) last_part = path_parts[-1] if path_parts else '' target = nested_dict.setdefault(last_part, {}) # 合并与上一层相同的 existing_items = target.get(folder_name, []) updated_items = sorted(set(existing_items + items)) target.update({folder_name: updated_items}) else: # 如果是在顶层,则直接更新最外层字典 dir_tree.update(current_level) return dir_tree ``` 这段代码定义了一个名为 `get_directory_structure()` 的辅助函数,它接收一个参数——要扫描的目标文件系统的绝对路径字符串 `rootdir`。这个函数通过调用内置模块 `os.walk()` 来迭代整个目录树,收集所有的文件子文件夹的名字,并按照它们所在的相对路径组织起来形成一个多维嵌套的数据结构[^1]。 #### 打印美观化的输出 为了让最终用户更容易理解所得到的结果,还需要编写另一个功能用来美化输出: ```python def pretty_print(data, indent=0): """打印出漂亮的缩进版文件/文件夹结构""" for key, value in data.items(): print(' ' * indent + str(key)) if isinstance(value, dict): pretty_print(value, indent+4) elif isinstance(value, list): for item in value: print(' ' * (indent + 4) + '- ' + str(item)) if __name__ == "__main__": project_root = './example_project' # 替换成你想查看的具体项目路径 structure = get_directory_structure(project_root) pretty_print(structure) ``` 上述脚本的最后一部分展示了如何使用这两个工具组合在一起工作:先调用 `get_directory_structure()` 函数获得项目的整体布局;再借助于自定义的 `pretty_print()` 方法按需调整格式后呈现出来。这样就可以清晰地看到各个级别的文件分布情况了。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值