Python: Turn List of Tuples into Dictionary of Nested Dictionaries -


so have bit of issue on hands. have list of tuples (made of level number , message) become html list. issues before happens, turn tuples values dictionary of nested dictionaries. here example:

# have list of tuples in format of (level_number, message) tuple_list = [(1, 'line 1'), (2, 'line 2'), (3, 'line 3'), (1, 'line 4')]  # , want turn a_dict = {     'line 1': {         'line 2': {             'line 3': {}         }     },      'line 4': {} } 

any appreciated, long valid python 3. thanks!

as pointed out in comment, should consider changing incoming data structure if have control @ on it. sequential list of tuples not ideal you're doing here. possible if treat tree. let's build (sane) data structure parse with

class node(object):     def __init__(self, name, level, parent=none):         self.children = []         self.name = name         self.level = level         self.parent = parent      def make_child(self, othername, otherlevel):         other = self.__class__(othername, otherlevel, self)         self.children.append(other)         return other 

now should able iterate on data structure in sensible way

def make_nodes(tuple_list):     """builds ordered grouping of nodes out of list of tuples     of form (level, name). returns last node.     """      curnode = node("root", level=-float('inf'))     # base node should first.      level, name in tuple_list:         while curnode.level >= level:             curnode = curnode.parent             # if we've done gone levels, go             # tree first parent can own         curnode = curnode.make_child(name, level)         # make node , move cursor     return curnode 

once structure complete, can iterate on it. doesn't matter here if go depth-first or breadth-first, let's dfs ease of implementation.

def parse_tree(any_node):     """given node in singly-rooted tree, returns dictionary     of form requested in question     """      def _parse_subtree(basenode):         """actually parsing, starting node given         root.         """          if not basenode.children:             # base case, if there no children return empty dict             return {}         subresult = {}         child in basenode.children:             subresult.update({child.name: _parse_subtree(child)})         return subresult      cursor = any_node     while cursor.parent:         cursor = cursor.parent         # finds root node     result = {}     child in cursor.children:         result[child.name] = _parse_subtree(child)     return result 

then feed in tuple list et voila

tuple_list = [(1, 'line 1'), (2, 'line 2'), (3, 'line 3'), (1, 'line 4')]  last_node = make_nodes(tuple_list) result = parse_tree(last_node) # {'line 1': {'line 2': {'line 3': {}}}, 'line 4': {}} 

Comments

Popular posts from this blog

javascript - Thinglink image not visible until browser resize -

firebird - Error "invalid transaction handle (expecting explicit transaction start)" executing script from Delphi -

mongodb - How to keep track of users making Stripe Payments -