Category tree implentation of lists in python -
Category tree implentation of lists in python -
im trying implement category tree unlimited depth of subcategories in python, have multiple list elements have create this..
let me explainin detail, list of list.
>mylists = [ >['home', 'desktop', 'mouse', 'wireless'], >['home', 'desktop', 'mouse', 'wired'], >['home', 'laptop', 'mouse'], >['home', 'laptop', '13-inch'], >]
i want output :
>home > desktop > mouse > wireless > wired > laptop > mouse > 13-inch
i understood should utilize recursive function iterate through lists , create magic ..
to achive , im doing task in 2 steps: 1. converting nested list nested dictionary (just maintain heirarchy) 2. converting nested dict desired formating explained above ..
step1: here code convert nested list nested dict:
>def make_rec_dict(dict): > d = {} > path in dict: > current_level = d > part in path: > if part not in current_level: > current_level[part] = {} > current_level = current_level[part] > #print part > homecoming d > >make_rec_dict(mylists) >{'home': {'laptop': {'mouse': {}, '13-inch': {}}, 'desktop': {'mouse': {'wireless': {}, 'wired': {}}}}}
step2 : display in desired format,
spaces = { 1 : '', 2 : '>>>>', 3 : '>>>>>>>>', 4 : '>>>>>>>>>>>>', 5 : '>>>>>>>>>>>>>>>>>>>>'} def display_recusively(dictionary, level=0): if type(dictionary) dict: values = [] # values , parse each 1 time again key, value in dictionary.iteritems(): if value != '': print spaces[level], key values.append(value) level = level + 1 homecoming display_recusively(values, level) elif value == '': # lastly kid print spaces[level], key elif type(dictionary) list: d in dictionary: homecoming display_recusively(d, level) else: print dictionary
but drawback of code is, cannot links of kid elements respect parents.. imean mouse , mouse should differnt , drawback of above code comming out of loop..
so please suggest me or right me improve way achieve:
1.formatted catergory tree depth levels 2.elements should carry parents create anchors tags (as explained in lastly paragragh)thanks , best , ravi
for same issue.. figured out way accomplish :), here changed code display_recursively():
def display_recusively(dictionary, level=0): if type(dictionary) dict: values = [] # values , parse each 1 time again key, value in dictionary.iteritems(): parent = key if value != '': # recurse when value dict print spaces[level], key values.append(value) level = level + 1 display_recusively(values, level) level = level -1 values = [] #sanitise list elif value == '': # lastly kid print spaces[level], key , "<>" elif type(dictionary) list: d in dictionary: display_recusively(d, level) level = level +1 else: print dictionary
python tree treeview category
Comments
Post a Comment