【发布时间】:2019-06-27 13:22:44
【问题描述】:
我想从我的 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': 'bot@nn.io', 'message': 'DB Dump {{ tasks(t1).result.filepath }} was stored to S3', 'subject': 'Prod DB Backup', 'to': 'admin@nn.io'}, '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)
因为这是嵌套的dict,我想从tasks dict到remove_key,那我做错了什么?
【问题讨论】:
-
您的主
data字典中嵌套了多个字典。name和description都是这些内部字典之一中的键,这就是它们没有被删除的原因。 -
您的字典只有两个您正在迭代的键,
full-workflow和version。 -
啊,好吧,嵌套字典,回到绘图板。
-
@PetarP 如果您对想要的操作有一个清晰的概念,您可以编辑您的问题。如果
name和description是任何嵌套字典中的键,是否要删除它们? -
@yuvgin 我想从
tasks中删除它们
标签: python python-3.x