簡體   English   中英

獲取嵌套字典中的鍵並將其關聯到遞歸 Python 3 的路徑

[英]fetching the key in a nested dictionary and associate it to the path of recursion Python 3

如何在未知長度的嵌套字典中提取鍵並將該鍵等同於遍歷路徑並將它們作為鍵值對存儲在另一個字典中。 我有一個嵌套字典如下

{
    "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的列表連接來跟蹤遞歸累積的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]'}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM