I am having trouble creating a tree hierarchy in Python 3. I'd like to be able to do this without using classes.
The data I need to start with is not in order and in the format ['ID','Parent']
:
data=[['E1', 'C1'],['C1', 'P1'],['P1', 'R1'],['E2', 'C2'],['C2', 'P2'],['P2', 'R1'],['C3', 'P2'],['E3', 'C4'],['C4', 'P3'],
['P3', 'R2'],['C5', 'P3'],['E4', 'C6'],['C6', 'P4'], ['P4', 'R2'],['E5', 'C7'],['C7', 'P5'],['P5', 'R3'],['E6', 'C9'],['C9', 'P6'],['P6', 'R3'],
['C8', 'P6'],['E7', 'C10'],['C10', 'P7'],['P7', 'R4'],['C11', 'P7'],['E8', 'C12'],['C12', 'P8'],['P8', 'R4']]
I want to create the (Tree) dictionary variable without the use of classes and end up with something like:
Tree={'R1':{'P1':{},'P2':{}},'R2':{}} etc
OR
Tree={'R1':[{'P1':[],'P2':[]}],'R2':[]} etc
Obviously R1 and R2 have more children than that but perhaps that's what the Tree structure would look like?
You can simply iterate over every child
,parent
tuple, create dictionary that maps the id's of the child and the parent to a list that contains the children of these elements. We keep doing this until we are done.
roots = set()
mapping = {}
for child,parent in data:
childitem = mapping.get(child,None)
if childitem is None:
childitem = {}
mapping[child] = childitem
else:
roots.discard(child)
parentitem = mapping.get(parent,None)
if parentitem is None:
mapping[parent] = {child:childitem}
roots.add(parent)
else:
parentitem[child] = childitem
Now that we have done that, roots
is a set of the ids of the tree roots: so for each such element we know that there is no id that is a parent. For each id in the roots
, we can simply fetch from the mapping
and that is a dictionary of the structure {'childid':child}
where childid
is the id (here a string
) and child
is again a dictionary of that form.
So you can print them like:
for root in roots:
print(mapping[root])
So in your case, the tree
is:
tree = { id : mapping[id] for id in roots }
For your sample data
, it generates:
>>> tree
{'R1': {'P1': {'C1': {'E1': {}}}, 'P2': {'C2': {'E2': {}}, 'C3': {}}}, 'R2': {'P4': {'C6': {'E4': {}}}, 'P3': {'C5': {}, 'C4': {'E3': {}}}}, 'R3': {'P6': {'C8': {}, 'C9': {'E6': {}}}, 'P5': {'C7': {'E5': {}}}}, 'R4': {'P8': {'C12': {'E8': {}}}, 'P7': {'C11': {}, 'C10': {'E7': {}}}}}
来源:https://stackoverflow.com/questions/42588346/recursively-creating-a-tree-hierarchy-without-using-class-object