Skip to content Skip to sidebar Skip to footer

Python: How To Loop Through All Unknown Depth Of A Tree?

I have a strategic issue of writing a program doing a job. I have CSV files like: Column1 Column 2 ------- ---------- parent1 [child1, child2, child3] parent2 [child4, child5,

Solution 1:

I would recommend a solution using two dictionaries. One nested one with the actually data structure you plan to convert to JSON, and one flat one that will let you actually find the keys. Since everything is a reference in Python, you can make sure that both dictionaries have the exact same values. Carefully modifying the flat dictionary will build your structure for you.

The following code assumes that you have already managed to split each line into a string parent and list children, containing values form the two columns.

json_dict = {}
flat_dict = {}

for parent, children infile_iterator():
    if parent in flat_dict:
        value = flat_dict[parent]
    else:
        value = {}
        flat_dict[parent] = json_dict[parent] = valuefor child in children:
        flat_dict[child] = value[child] = {}

Running this produces json_dict like this:

{
    'parent1': {
        'child1': {
            'child7': {},
            'child8': {}
        },
        'child2': {},
        'child3': {}
    },
    'parent2': {
        'child4': {},
        'child5': {
            'child10': {},
            'child33': {}
        },
        'child6': {}
    }
}

Here is an IDEOne link to play with.

Post a Comment for "Python: How To Loop Through All Unknown Depth Of A Tree?"