Home > other >  Retrieve all keys of a nested dictionary (arbitrirary length and depth) with name of key dictating p
Retrieve all keys of a nested dictionary (arbitrirary length and depth) with name of key dictating p

Time:10-23

Let's say I have the following dictionary:

{
'a1': {'b1': {'c1': 'val'}, 'b2': { 'c2': { 'd2': 'terminal'} } },
'a2': {'b2': 'val'}
}

My goal would be to retreieve all of the keys in a list:

'a1', 'b1', 'c1', 'b2', 'c2', 'd2', 'a2', 'b2'

but then also preserve their position in the dictionary, something like this:

'a1', 'a1.b1', 'a1.b1.c1', 'a1.b2', 'a1.b2.c2', 'a1.b2.c2.d2', 'a2', 'a2.b2'

Is this possible in Python

CodePudding user response:

One approach is to use a recursive generator function:

data = {
    'a1': {'b1': {'c1': 'val'}, 'b2': {'c2': {'d2': 'terminal'}}},
    'a2': {'b2': 'val'}
}


def nested_iter(d, root=""):
    for key, value in d.items():
        printable = f"{root}.{key}" if root else key
        if isinstance(value, dict):
            yield printable
            yield from nested_iter(value, root=printable)
        else:
            yield printable


print(list(nested_iter(data)))

Output

['a1', 'a1.b1', 'a1.b1.c1', 'a1.b2', 'a1.b2.c2', 'a1.b2.c2.d2', 'a2', 'a2.b2']

As an alternative you could use collections.deque to handle the recursion:

def nested_iter_with_deque(d):
    from collections import deque
    result = []
    q = deque(d.items())
    while q:
        k, vs = q.popleft()
        result.append(k)
        if isinstance(vs, dict):
            lst = [(f"{k}.{key}", value) for key, value in vs.items()]
            if lst:
                q.extendleft(deque(lst))

    return result


print(nested_iter_with_deque(data))

Output

['a1', 'a1.b2', 'a1.b2.c2', 'a1.b2.c2.d2', 'a1.b1', 'a1.b1.c1', 'a2', 'a2.b2']
  • Related