首页 > 解决方案 > 将字典附加到嵌套字典 Python 3.6

问题描述

我有一个嵌套的 Python 字典,看起来像这样

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

我还有一个已转换为字典的数据框,如下所示。

[{'source': 'FLEXCAB', 'app': 'Replicator', 'feed_id': 2382, 'seq_type': 'SEQUENCE', 'hdfs_home_dir': '/data/b2b'}]

我希望将此字典附加到嵌套的 Python 字典master_config_skeleton中以将其转换如下:-

master_config_skeleton = {
"ingestion_config":
    {
    "source": "FLEXCAB",
    "app": "Replicator",
    "feed_id": "2382",
    "seq_type": "SEQUENCE",
    "hdfs_home_dir": "/data/b2b",
    "location":{}, 
    "start_sequence":{}, 
    "datafeed":
        {
        "t04047":
            {
            "validation":
                {
                "triple_check":{},
                "record_count_validation":{}
                }, 
            "date_pattern":{}, 
            "cdc_config": {}
            }
        }
    }
}

标签: python-3.xpandasdictionary

解决方案


从列表的第一个值和merge一起创建字典:

L = [{'source': 'FLEXCAB', 'app': 'Replicator', 'feed_id': 2382, 
      'seq_type': 'SEQUENCE', 'hdfs_home_dir': '/data/b2b'}]

#https://stackoverflow.com/a/7205107    
out = merge(master_config_skeleton, {'ingestion_config':L[0]})
print (out)

{
  "ingestion_config": {
    "location": {},
    "start_sequence": {},
    "datafeed": {
      "t04047": {
        "validation": {
          "triple_check": {},
          "record_count_validation": {}
        },
        "date_pattern": {},
        "cdc_config": {}
      }
    },
    "source": "FLEXCAB",
    "app": "Replicator",
    "feed_id": 2382,
    "seq_type": "SEQUENCE",
    "hdfs_home_dir": "/data/b2b"
  }
}

推荐阅读