Search code examples
pythondictionarynestedkey

From a given nested dictionary, find all the nested keys sequences


I have a nested dictionary which looks like this:

dct = {"A": {"AA": "aa", "BB": {"BBB": "bbb", "CCC": "ccc"}}}

I want to extract all the key sequences in the list format till I reach the deepest key:value pair.

The expected output is something like this:

["A->AA", "A->BB->BBB", "A->BB->CCC"]

The solution I tried is:

    for k, v in dct.items():
        if isinstance(v, dict):
            # traverse nested dict
            for x in find_keys(v):
                yield "{}_{}".format(k, x)
                print("{}_{}".format(k, x))
        else:
            yield k
            print(k)

but it doesnot seem to work as expected.


Solution

  • I guess you are almost there (or omitted some parts by mistake):

    def find_keys(dct):
        for k, v in dct.items():
            if isinstance(v, dict):
                yield from (f"{k}->{x}" for x in find_keys(v))
            else:
                yield k
    
    dct = {"A": {"AA": "aa", "BB": {"BBB": "bbb", "CCC": "ccc"}}}
    print(*find_keys(dct)) # A->AA A->BB->BBB A->BB->CCC
    

    If you want to use return instead, then:

    def find_keys(dct):
        result = []
        for k, v in dct.items():
            if isinstance(v, dict):
                result += [f"{k}->{x}" for x in find_keys(v)]
            else:
                result.append(k)
        return result