Search code examples
pythondictionarynested

Finding the max dict value of a 3-level nested dict


I have a 3-level nested dict and I would like to find the max value of the 3rd-level dict and have it mapped to the 2nd-level key it belongs to. For example, In "Loc-1" dict value, there are two 2nd-level keys that are "36", I want this key mapped to the value "56".

This is the dict:

{
    "Loc-1": {
        "A-1": {"36" : {"value" : "34"}},
        "A-2": {"36" : {"value" : "56"}},
        "A-3": {"48" : {"value" : "72"}},
        "A-4": {"100" : {"value" : "77"}},
        "A-5": {"48" : {"value" : "2"}},
        "A-6": {"100" : {"value" : "10"}},
        "A-7": {"44" : {"value": "21"}}
        
    }
    
    "Loc-2": {
        "A-8": {"44" : {"value" : "52"}},
        "A-9": {"48" : {"value" : "23"}},
        "A-10": {"40" : {"value" : "62"}},
        "A-11": {"153" : {"value" : "43"}},
        "A-12": {"40" : {"value" : "22"}},
        "A-13": {"153" : {"value" : "10"}},
        "A-14": {"36" : {"value": "21"}}
        
    }

}

This is the desired state:

{ 
    "Loc-1": {   
        "36" : "56",
        "48" : "72",
        "100": "77",
        "44" : "21"
        
    }
    
    "Loc-2": { 
        "36" : "21",
        "40" : "62",
        "48" : "23",
        "44" : "52",
        "153": "43",
        
    }
    
}

I'm finding it hard to compare one value to all the other values with the same key when it nested like this. How can I accomplish this?


Solution

  • Nested loops will work:

    results = {}
    
    # 1st level: "Loc-1", "Loc-2"
    for key1 in data:
        # Initialize to empty dictionary
        results[key1] = {}
        # 2nd level: A-1, A-2, etc
        for key2 in data[key1]:
            # First key 3rd level: 38, 36, etc
            key3 = next(iter(data[key1][key2]))
            value = data[key1][key2][key3]["value"]
            # Set max if already in results or just add
            if key3 in results[key1]:
                results[key1][key3] = max(results[key1][key3], value)
            else:
                results[key1][key3] = value