rrmerugu
rrmerugu

Reputation: 1896

Category tree implementation of lists in python

I'm trying to implement category tree with an unlimited depth of subcategories in Python, I have multiple list elements from which I have to make this.

Let me explain in detail, this is my list of list.

>mylists = [
>['home', 'desktop', 'mouse', 'wireless'],
>['home', 'desktop', 'mouse', 'wired'],
>['home', 'laptop', 'mouse'],
>['home', 'laptop', '13-inch'],
>]

I want the output to be:

>home
>   desktop
>        mouse
>            wireless
>            wired
>   laptop
>       mouse
>       13-inch

I understood that I should use a recursive function to iterate through the lists and make something magic.

To achieve this, I am doing this task in 2 steps: 1. converting this nested list into nested dictionary (just to keep the hierarchy) 2. converting the nested dict into the desired formatting explained above.

Step1: Here is my code to convert nested list into nested dict:

>def make_rec_dict(dict):
>    d = {}
>    for path in dict:
>        current_level = d
>        for part in path:
>            if part not in current_level:
>                current_level[part] = {}
>            current_level = current_level[part]
>            #print part
>    return d
>
>make_rec_dict(mylists)
>{'home': {'laptop': {'mouse': {}, '13-inch': {}}, 'desktop': {'mouse': {'wireless': {}, 'wired': {}}}}}

Step2: To display in the desired format,

spaces = { 1 : '', 2 : '>>>>', 3 : '>>>>>>>>', 4 : '>>>>>>>>>>>>', 5 : '>>>>>>>>>>>>>>>>>>>>'}
def display_recusively(dictionary, level=0):
    if type(dictionary) is dict: 
        values = []  # get all the values and parse each again
        for key, value in dictionary.iteritems():
            if value != '':
                print spaces[level], key
                values.append(value)
                level = level + 1
                return display_recusively(values, level)
            elif value == '':  # this is the last child
                print spaces[level], key

    elif type(dictionary) is list: 
        for d in dictionary:
            return display_recusively(d, level)
    else:
        print dictionary

But the drawback of the code is, I cannot get the link of the child elements with respect to the parents. I mean Mouse and Mouse should be different and the drawback of the above code is its coming out of the loop..

So please suggest me or correct me a better way to achieve:

Upvotes: 2

Views: 2653

Answers (2)

balavignesh
balavignesh

Reputation: 1

Same output can be got by doing this-

my_lists = [['home', 'desktop', 'mouse', 'wireless'], ['home', 'desktop', 'mouse', 'wired'],
            ['home', 'laptop', 'mouse'], ['home', 'laptop', '13-inch']]

path_list = []

for lists in my_lists:

    path = ''
    for i in range(len(lists)):
        path = path + lists[i]
        if path not in path_list:
            print '  '*i + lists[i]
            path_list.append(path)

Upvotes: 0

rrmerugu
rrmerugu

Reputation: 1896

For anyone with same issue.. i figured out the way to achieve this :), here is the changed code for display_recursively():

def display_recusively(dictionary, level=0):
    if type(dictionary) is dict: 
        values = []  # get all the values and parse each again
        for key, value in dictionary.iteritems():
            parent = key
            if value != '': # recurse only when value is dict
                print spaces[level], key 
                values.append(value)
                level = level + 1
                display_recusively(values, level) 
                level = level -1 
                values = [] #sanitise the list
            elif value == '':  # this is the last child
                print spaces[level], key , "<>"

    elif type(dictionary) is list: 
        for d in dictionary:
            display_recusively(d, level)
            level = level +1
    else:
        print dictionary

Upvotes: 1

Related Questions