Home > OS >  From a given nested dictionary, find all the nested keys sequences
From a given nested dictionary, find all the nested keys sequences

Time:12-08

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.

CodePudding user response:

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
  • Related