Search code examples
pythondictionarynested

Searching top keys based on values of nested dicts on python


There are many questions that cover similars concets, but not this especifically. I use nested dicts, two levels, all values are unique and need to find the root key based on a value inside a child dict. I have a code, but it feels not optimal. Care to help?

Exemple dict:

maindict = {"First Node"  : {0: "00", 1: "01", 2: "02", 3: "03"},
        "Second Node" : {0: "10", 1: "11", 2: "12", 3: "13"},
        "Third Node"  : {0: "20", 1: "21", 2: "22", 3: "33"}}

def search_root(val):
    for i, dict in enumerate(list(maindict.values())):
        if val in list(dict.values()):
            return list(maindict.keys())[i] 

I feel like this for loop and if statement could be simplyfied somehow but I don't have the knowledge to do it.


Solution

  • I don't think you can escape a loop in this case in any reasonable way, but you can make things clearer and (maybe) avoid some conversions,

    def find_root(target_val, maindict):
        for key, val in maindict.items():
            if target_val in maindict[key].values():
                return key
    
    maindict = {"First Node"  : {0: "00", 1: "01", 2: "02", 3: "03"},
            "Second Node" : {0: "10", 1: "11", 2: "12", 3: "13"},
            "Third Node"  : {0: "20", 2: "11", 2: "22", 3: "23"}}
    
    target_val = "22"
    
    target_node = find_root(target_val, maindict)
    

    The above takes advantage of dictionary-specific functionality. Also, avoid calling variables dict, list etc. since those are Python builtin names for those data structures.