用dict理解python删除多个关键项

问题描述 投票:3回答:2

我想从json中删除多个键,并且正在使用像这样的字典理解功能>>

remove_key = ['name', 'description']

    data = {'full-workflow': {'task_defaults': {'retry': {'count': 3, 'delay': 2}}, 'tasks': {'t1': {'action': 'nn.postgres.export-db', 'description': 'Dump prod DB with default settings', 'input': {'database': 'prod', 'filepath': '/var/tmp/prod-dump.pgsql', 'host': 'postgres.local', 'password': 'mypass', 'username': 'myuser'}, 'name': 'db export', 'on-success': ['t2']}, 't2': {'action': 'nn.aws.upload-to-s3', 'description': 'Upload to S3 bucket for development', 'input': {'sourcepath': '{{ tasks(t1).result.filepath }}', 'targetpath': 's3://mybucket/prod-dump.pgsql'}, 'name': 'Upload to S3', 'on-success': ['t3'], 'retry': {'count': 5, 'delay': 5}}, 't3': {'action': 'nn.shell.command', 'description': 'Remove temp file from batch folder ', 'input': {'cmd': 'rm {{ tasks(t1).result.filepath }}'}, 'name': 'Remove temp file', 'on-complete': ['t4']}, 't4': {'action': 'nn.notify.send-mail', 'description': 'Send email to admin containing target path', 'input': {'from': '[email protected]', 'message': 'DB Dump {{ tasks(t1).result.filepath }} was stored to S3', 'subject': 'Prod DB Backup', 'to': '[email protected]'}, 'name': 'Send email', 'target': 'nn'}}}, 'version': '2'}

    def remove_additional_key(data):
        return {
            key: data[key] for key in data if key not in remove_key
        }

然后只是

new_data = remove_additional_key(data)

因为这是嵌套字典,所以我想从remove_key字典中复制tasks,所以我在做什么错?

我想从json中删除多个键,并且我正在使用字典理解,例如remove_key = ['name','description'] data = {'full-workflow':{'task_defaults':{'retry': {'count':3,...

python python-3.x
2个回答
2
投票

您的数据是嵌套字典。如果要使用remove_key中包含的键删除任何数据,则建议使用递归方法。这可以根据您现有的功能remove_additional_key轻松实现:


1
投票

您有一本带有一些嵌套词典的字典。如果您确切知道要删除哪些键,则可以使用:

© www.soinside.com 2019 - 2024. All rights reserved.