[Solved] Iterate over a list to create a parent/child dictionary [closed]


Assuming each name belongs to only one key, and parents are defined before their children, you need to do three tasks for each element:

  1. map its name to a yet incomplete child list
  2. map its ID to its name
  3. link it to its parent

If parents and children are not ordered, i.e. a child can appear before its parent, you must build 1. and 2. separately from 3.
Otherwise, you can do everything in one pass over your data. Note that instead of indexing into elements, you can destructure the element in the for loop.

key2name = {}
name2children = {}
for key, name, parent in l:
    name2children[name] = []  # 1.
    key2name[key] = name      # 2.
    if parent != 'P':         # root node has no parent
        name2children[key2name[parent]].append(name) # 3.

For your example, this produces the structure

{'pharma': ['y', 'x'], 'x': ['z'], 'y': [], 'z': []}

Note that your data is not sorted to match your desired output!


You can pretty print this as desired by walking this tree. The sorted call can be dropped if you do not care about ordering.

def printwalk(node, indent=0):
    print(' '*indent, node)
    for child in sorted(name2children[node]):
        printwalk(child, indent+1)
printwalk('pharma')
# pharma
#  x
#   z
#  y

This is the case if parents and children are not ordered. You must separately initialise the translation (1) and parent->child (2) containers.

key2name = {}
name2children = {}
for key, name, _ in l:
    name2children[name] = []  # 1.
    key2name[key] = name      # 2.

for key, name, parent in l:
    if parent != 'P':         # root node has no parent
        name2children[key2name[parent]].append(name) # 3.

2

solved Iterate over a list to create a parent/child dictionary [closed]