简体   繁体   中英

How to check if data exists from multiple nested dict using Python

There are data with multiple nested structures as follows.

base = [
  {'id': 1, 'child_categories': [
    {'id': 11, 'child_categories': [
      {'id': 111, 'child_categories': [
        {'id': 1111, 'child_categories': []}
      ]},
    ]},
    {'id': 9999, 'child_categories': [
      {'id': 121, 'child_categories': []}
    ]},
  ]},
  {'id': 2, 'child_categories': [
    {'id': 21, 'child_categories': []},
  ]},
  {'id': 3, 'child_categories': [
    {'id': 31, 'child_categories': [
      {'id': 311, 'child_categories': []},
      {'id': 9999, 'child_categories': []},
    ]},
  ]},
  {'id': 4, 'child_categories': [], 'other_data': [
    {'id':9999, 'detail': 'detail_text'}
  ]},
  {'id': 9999, 'child_categories': [
    {'id': 333, 'child_categories': []},
  ]},
]

I want to implement processing to confirm that data of id: 9999 exists from this data and delete it if it exists.
As a result of processing the image below is imagined.

result = [
  {'id': 1, 'child_categories': [
    {'id': 11, 'child_categories': [
      {'id': 111, 'child_categories': [
        {'id': 1111, 'child_categories': []}
      ]},
    ]}
  ]},
  {'id': 2, 'child_categories': [
    {'id': 21, 'child_categories': []},
  ]},
  {'id': 3, 'child_categories': [
    {'id': 31, 'child_categories': [
      {'id': 311, 'child_categories': []}
    ]},
  ]},
  {'id': 4, 'child_categories': [], 'other_data': [
    {'id':9999, 'detail': 'detail_text'}
  ]}
]

As a problem, rarely there is data like 'other_data': [{'id': 9999, 'detail': 'detail_text'}] .
In this case I do not want to delete that data.
To the last, it is targeting data of 'id': 9999 at the first level in the list or data of id': 9999 within 'child_categories' .

Currently, I can only imagine the process of writing for many times.
I hope you will tell me a good way.

Looks like you need some kind of recursive function like this:

def filter_data(data, id):
    " WARNING: this will edit data in-place! "
    for i, node in enumerate(data):
        if node['id'] == id:
            del data[i]
        leaves = node.get('child_categories')
        if leaves:
            filter_data(leaves, id)

filter_data(base, id=9999)
print(base)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM