Holen Sie sich ein bestimmtes Subdic in einem verschachtelten Dic basierend auf dem Schlüssel

Dec 19 2020

Ich habe ein verschachteltes Wörterbuch. Und ich möchte ein Unterwörterbuch basierend auf einem bestimmten Attribut extrahieren: Hier ist eine einfachere Version meines Wörterbuchs:

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": []
                  }]}]}]}]}]]}]}]}

Und basierend auf zB "Akronym": "FRP" möchte ich dieses bestimmte Wörterbuch und alle seine Kinder so bekommen:

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": []
}]}

Ich habe den folgenden Code ausprobiert (aus dem Vorschlag von Aplet123), aber er scheint das Wörterbuch nicht zurückzugeben. Es wird nur True zurückgegeben. Mache ich etwas falsch?

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")

Antworten

1 Aplet123 Dec 19 2020 at 05:24

Sie können eine Tiefensuche verwenden:

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