更新嵌套字典的正确方法是什么,所以我有两个字典
data = {
'version': '2',
'workflow': {'task_defaults': {'retry': {'count': 3, 'delay': 2}},
'tasks': {'t1': {'action': 'postgres.export-db',
'input': {'database': 'prod',
'filepath': '/var/tmp/prod-dump.pgsql',
'host': 'postgres.local',
'password': 'mypass',
'username': 'myuser'},
'on-success': ['t2']},
't2': {'action': 'aws.upload-to-s3',
'input': {'sourcepath': '{{ tasks(t1).result.filepath }}',
'targetpath': 's3://mybucket/prod-dump.pgsql'},
'on-success': ['t3'],
'retry': {'count': 5, 'delay': 5}},
't3': {'action': 'shell.command',
'input': {'cmd': 'rm {{ tasks(t1).result.filepath }}'},
'on-complete': ['t4']},
't4': {'action': 'notify.send-mail',
'input': {'from': 'bot@njinn.io',
'message': 'DB Dump {{ tasks(t1).result.filepath }} was stored to S3',
'subject': 'Prod DB Backup',
'to': 'admin@njinn.io'},
'target': 'njinn'}}}}
和另一个
new_data = {'action': '/srv/foo/', 'pack': 'name'}
所以我想将new_data
合并到input
中的data
字典中。
所以input
看起来像这样
{"input": {
"action": "/srv/foo",
"pack": "name",
"target": "foo",
"parameters": {
"to": "admin@foo.io",
"from": "bot@foo.io",
"subject": "Prod DB Backup",
"message": "DB Dump was stored to S3"
}
}
我怎么能做到,所有尝试都失败了,我拥有的最佳解决方案是
{key:dict(data.get(key,{}), **values) for key,values in new_data.items()}
但是那没有用,有人可以解释如何做,谢谢。
答案 0 :(得分:1)
只需使用双星符号!如果您只想合并这两个字典:
for key in data['workflow']['tasks']:
data['workflow']['tasks'][key]['input'] = {**new_data, **data['workflow']['tasks'][key]['input']}
如果您希望字典看起来像您的示例(使用parameters
):
for key in data['workflow']['tasks']:
data['workflow']['tasks'][key]['input'] = {**new_data, 'parameters': data['workflow']['tasks'][key]['input']}