How to create this data structure

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Mrpaolosarino

I have a node in which it has 3 child and in that child, I have 2 child:

Node
   Child
       Grandchild
       Grandchild
   Child
       Grandchild
       Grandchild
   Child
       Grandchild
       Grandchild

I want to illiterate it and get:

{{Node:{Child:[Grandchild,Grandchild]}} , {Node:{Child:[Grandchild,Grandchild]}} , {Node:{Child:[Grandchild,Grandchild]}}}

Anyone knows how to for loop this shit?? this is bothering me for days. If my approach is wrong feel free to correct me.

:bust_in_silhouette: Reply From: exuin

I’m not sure what your data structure is supposed to be - it looks like some kind of dictionary - array hybrid. Dictionaries need unique keys to work, and your dictionary doesn’t have any keys in the outer dictionary. Either do something like this:

var dictionary = {
    "Child1": [Grandchild1, Grandchild2],
    "Child2": [Grandchild1, Grandchild2],
    "Child3": [Grandchild1, Grandchild2],
}

Or do something like this:

var array = [
    [Grandchild1, Grandchild2],
    [Grandchild1, Grandchild2],
    [Grandchild1, Grandchild2],
]

Also, the term is “iterate” and not “illiterate”. To get the dictionary, do this:

var dictionary = {}
for child in node.get_children():
    var arr = []
    for grandchild in child.get_children():
        arr.append(grandchild)
    dictionary[child.name] = arr

To get the array, do this:

var array = []
for child in node.get_children():
    var arr = []
    for grandchild in child.get_children():
        arr.append(grandchild)
    array.append(arr)

Holy fuck it works!! Thanks ! My initial problem is that the value replaces over and over because of iteration but boy it’s because I do avar arr = [] inside
the for grandchild in child.get_children() . Thank you very much

Mrpaolosarino | 2021-04-14 01:02