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?
{'ID': 1, 'ID': 2}, you will end up with{'ID': 2}because the second'ID'will overwrite the first one.dictis—and it's fairly easy to create adictsubclass that would make doing what you want to do very easy. See What is the best way to implement nested dictionaries?