Skip to main content
 首页 » 编程设计

python之在嵌套字典中获取键并将其关联到递归 Python 3 的路径

2024年11月24日13cmt

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

{ 
    "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

请您参考如下方法:

您可以对生成器使用递归。在函数的签名中,保留了一个默认参数,用于跟踪每次调用 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]'}