dapatkan subdik tertentu di dic bersarang berdasarkan kunci

Dec 19 2020

Saya memiliki kamus bersarang. Dan saya ingin mengekstrak sub kamus berdasarkan atribut tertentu: Berikut ini versi kamus saya yang lebih sederhana:

subdata = {
     "id": 997,
     "acronym": "root",
     "color_hex_triplet": "FFFFFF",
     "children": [
      {
       "id": 8,
       "acronym": "grey",
       "color_hex_triplet": "BFDAE3",
       "children": [
        {
         "id": 567,
         "acronym": "CH",
         "color_hex_triplet": "B0F0FF",
         "children": [
          {
           "id": 688,
           "acronym": "CTX",
           "color_hex_triplet": "B0FFB8",
           "children": [
            {
             "id": 695,
             "acronym": "CTXpl",
             "color_hex_triplet": "70FF70",
             "children": [
              {
               "id": 315,
               "acronym": "Isocortex",
               "color_hex_triplet": "70FF71",
               "children": [
                {
                 "id": 184,
                 "acronym": "FRP",
                 "color_hex_triplet": "268F45",
                 "children": [
                  {
                   "id": 68,
                   "acronym": "FRP1",
                   "color_hex_triplet": "268F45",
                   "children": []
                  },
                                    {
                   "id": 69,
                   "acronym": "FRP2",
                   "color_hex_triplet": "268F45",
                   "children": []
                  }]}]}]}]}]]}]}]}

Dan berdasarkan misalnya "akronim": "FRP" saya ingin mendapatkan kamus tertentu itu dan semua anaknya seperti ini:

region_dict = {
"id": 184,
"acronym": "FRP",
"color_hex_triplet": "268F45",
"children": [
{
"id": 68,
"acronym": "FRP1",
"color_hex_triplet": "268F45",
"children": []},
{"id": 69,
"acronym": "FRP2",
"color_hex_triplet": "268F45",
"children": []
}]}

Saya mencoba kode berikut (dari saran Aplet123), tetapi sepertinya tidak mengembalikan kamus. Itu hanya mengembalikan True. Apakah saya melakukan sesuatu yang salah?

def get_parent_dict(dic, reg):
    if dic['acronym'] == reg:
        return dic
    for child in dic["children"]:
        result = get_parent_dict(child, reg) is not None
        if result is not None:
            return result
    return None # not technically needed

f = open(json_path) 
data = json.load(f) 

subdata = data['msg'][0] #this is a nested dictionary

region_dict = get_parent_dict(subdata, "FRP")

Jawaban

1 Aplet123 Dec 19 2020 at 05:24

Anda dapat menggunakan pencarian pertama yang mendalam:

def dfs_for_id(dic, id):
    if dic["id"] == id:
        return dic
    for child in dic["children"]:
        result = dfs_for_id(child, id)
        if result is not None:
            return result
    return None # not technically needed