Removing mulitple key items with dict comprehension python
我想从我的
1 2 3 4 5 6 7 8 | remove_key = ['name', 'description'] data = {'full-workflow': {'task_defaults': {'retry': {'count': 3, 'delay': 2}}, 'tasks': {'t1': {'action': 'njinn.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': 'njinn.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': 'njinn.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': 'njinn.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': 'njinn'}}}, 'version': '2'} def remove_additional_key(data): return { key: data[key] for key in data if key not in remove_key } |
然后只是
1 | new_data = remove_additional_key(data) |
因为这是嵌套的dict,所以我想从
您的数据是嵌套字典。如果您想删除任何包含在
1 2 3 4 5 6 7 8 9 10 11 12 | def remove_additional_key(data): sub_data = {} for key in data: if key not in remove_key: if isinstance(data[key], dict): # if is dictionary sub_data[key] = remove_additional_key(data[key]) else: sub_data[key] = data[key] return sub_data new_data = remove_additional_key(data) |
注:如果条目是字典,则可以由
你有一本字典,里面有几个嵌套的字典。如果您确切知道要删除哪些子分区,可以使用:
然而,在字典理解中使用查找方法(
如果您不知道嵌套字典的确切路径,可以使用函数(为方便起见发布另一个答案)。
1 2 3 4 5 6 7 8 9 10 11 | def delete_keys_from_dict(d, lst_keys): for k in lst_keys: try: del dict_del[k] except KeyError: pass for v in dict_del.values(): if isinstance(v, dict): delete_keys_from_dict(v, lst_keys) return dict_del |
然后你可以打电话
不用说,如果在多个嵌套字典中有