获取嵌套字典中的键并将其与递归python3的路径相关联

2024-09-27 22:22:49 发布

您现在位置:Python中文网/ 问答频道 /正文

如何在长度未知的嵌套字典中提取密钥,并将该密钥与遍历路径相等,并将它们作为键值对存储在另一个字典中。我有一个嵌套字典如下

{
    "ingestion_config": {
        "location": {},
        "start_sequence": {},
        "datafeed": {
            "t04047": {
                "validation": {
                    "triple_check": {},
                    "record_count_validation": {}
                },
                "date_pattern": {},
                "cdc_config": {}
            }
        }
    }
}

我希望在不同的层次上获取密钥,并将其等同于下面的遍历路径

{
ingestion_config: [ingestion_config]
location: [ingestion_config][location],
start_sequence: [ingestion_config][start_sequence],
datafeed: [ingestion_config][datafeed]
t04047: [ingestion_config][datafeed][t04047]
triple_check: [ingestion_config][data_feed][t04047][validation][trip_check]
}

我找到的与我类似的场景最接近的帖子是: here


Tags: 路径config字典check密钥locationrecordstart
1条回答
网友
1楼 · 发布于 2024-09-27 22:22:49

可以对生成器使用递归。在函数的签名中,保留了一个默认参数,用于跟踪递归在每次调用paths时通过列表串联累积的路径:

d = {'ingestion_config': {'location': {}, 'start_sequence': {}, 'datafeed': {'t04047': {'validation': {'triple_check': {}, 'record_count_validation': {}}, 'date_pattern': {}, 'cdc_config': {}}}}}
def paths(_d, _c = []):
  for a, b in _d.items():
    yield _c+[a]
    yield from paths(b, _c+[a])

results = {i[-1]:''.join(f'[{a}]' for a in i) for i in paths(d)}

输出:

{'ingestion_config': '[ingestion_config]', 'location': '[ingestion_config][location]', 'start_sequence': '[ingestion_config][start_sequence]', 'datafeed': '[ingestion_config][datafeed]', 't04047': '[ingestion_config][datafeed][t04047]', 'validation': '[ingestion_config][datafeed][t04047][validation]', 'triple_check': '[ingestion_config][datafeed][t04047][validation][triple_check]', 'record_count_validation': '[ingestion_config][datafeed][t04047][validation][record_count_validation]', 'date_pattern': '[ingestion_config][datafeed][t04047][date_pattern]', 'cdc_config': '[ingestion_config][datafeed][t04047][cdc_config]'}

相关问题 更多 >

    热门问题