我有一本看起来像这样的嵌套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": {}
}
}
}
}
答案 0 :(得分:1)
从list的第一个值和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"
}
}
答案 1 :(得分:0)
您可以使用dict的update方法,它从另一个词典中获取所有键并将其添加到原始词典中,请注意此方法会覆盖现有键
例如此代码
d1 = {'A': 'Alice', 'B': 'Bob'}
d2 = {'B': 'Barak', 'C': 'Carl'}
d1.update(d2)
print(d1)
将打印此输出
{'A': 'Alice', 'B': 'Barak', 'C': 'Carl'}