I need a function to take this dictionary of lists and produce a hierarchical dictionary. I always have the root key so the function can be called with the root key as an argument. There are no circular references. If an item has no children it should return 'DATA'.
I am almost there but in my result those keys that have a dictionary as child node end up added a second time as a child to itself.
flat = {'g': ['h', 'i', 'j'],
'b': ['e', 'f', 'g', 'm'],
'a': ['b', 'c', 'd'],
'm': ['n', 'o', 'p']}
what_the_result_should_be = {'a': {'c': 'DATA','d': 'DATA', 'b': {'m':{'n': 'DATA', 'o': 'DATA', 'p': 'DATA'}, 'e': 'DATA','f': 'DATA','g':{'h': 'DATA', 'i': 'DATA', 'j': 'DATA'}}}}
def walk(d, node):
if d.get(node, None):
return {node : {child : walk(d, child) for child in d[node]}}
else:
return 'DATA'
what_my_attempt_produces = walk(flat, 'a')