Home > Software design >  For a given dictionary key, get all the subordinates as a list [closed]
For a given dictionary key, get all the subordinates as a list [closed]

Time:09-17

Given the following data structure

T = {'a': ['b','c'], 'c': ['d', 'r'], 's': ['k']}

I need all elements of a given key.

Example:

print(get_hierarchy(T, 'a'))

Output:

['b','c','d','r']

How can I get the final output?

CodePudding user response:

If I understand you correctly you want a recursive function:

def get_hierarchy(d, val):
    out = d.get(val, [])
    for v in out:
        out.extend(get_hierarchy(d, v))
    return out


T = {"a": ["b", "c"], "c": ["d", "r"], "s": ["k"]}
print(get_hierarchy(T, "a"))

Prints:

['b', 'c', 'd', 'r']
  • Related