[英]Python: Turn List of Tuples into Dictionary of Nested Dictionaries
所以我手头有点问题。 我有一个元组列表(由级别编号和消息组成),最终将成为一个 HTML 列表。 我的问题是,在这发生之前,我想将元组值转换为嵌套字典的字典。 所以这里是例子:
# I have this list of tuples in format of (level_number, message)
tuple_list = [(1, 'line 1'), (2, 'line 2'), (3, 'line 3'), (1, 'line 4')]
# And I want to turn it into this
a_dict = {
'line 1': {
'line 2': {
'line 3': {}
}
},
'line 4': {}
}
任何帮助将不胜感激,只要它是有效的 Python 3。谢谢!
正如我在评论中指出的那样,如果您有任何控制权,您应该强烈考虑更改传入的数据结构。 元组的顺序列表绝对不适合您在此处执行的操作。 然而,如果你把它当作一棵树来对待,这是可能的。 让我们构建一个(理智的)数据结构来解析它
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
现在您应该能够以某种合理的方式迭代您的数据结构
def make_nodes(tuple_list):
"""Builds an ordered grouping of Nodes out of a list of tuples
of the form (level, name). Returns the last Node.
"""
curnode = Node("root", level=-float('inf'))
# base Node who should always be first.
for level, name in tuple_list:
while curnode.level >= level:
curnode = curnode.parent
# if we've done anything but gone up levels, go
# back up the tree to the first parent who can own this
curnode = curnode.make_child(name, level)
# then make the node and move the cursor to it
return curnode
一旦您的结构完成,您就可以对其进行迭代。 如果您采用深度优先或广度优先,这里并不重要,所以让我们做一个 DFS 只是为了便于实现。
def parse_tree(any_node):
"""Given any node in a singly-rooted tree, returns a dictionary
of the form requested in the question
"""
def _parse_subtree(basenode):
"""Actually does the parsing, starting with the node given
as its root.
"""
if not basenode.children:
# base case, if there are no children then return an empty dict
return {}
subresult = {}
for child in basenode.children:
subresult.update({child.name: _parse_subtree(child)})
return subresult
cursor = any_node
while cursor.parent:
cursor = cursor.parent
# finds the root node
result = {}
for child in cursor.children:
result[child.name] = _parse_subtree(child)
return result
然后输入你的元组列表等等
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': {}}
假设您只有三个级别,则可以执行以下操作:
tuple_list = [(1, 'line 1'), (2, 'line 2'), (3, 'line 3'), (1, 'line 4')]
a_dict = {}
for prio, key in tuple_list:
if prio == 1:
a_dict[key] = {}
first_level = key
if prio == 2:
a_dict[first_level][key] = {}
second_level = key
if prio == 3:
a_dict[first_level][second_level][key] = {}
# So on ...
print a_dict
这也假设层次结构按顺序列出,这意味着级别 1、级别 1'、级别 2、级别 3 将是级别 1 的单个 dict,以及级别顺序,如级别 1' -> 级别 2 -> 级别 3。所以下列
tuple_list = [(1, 'line 5'), (1, 'line 1'), (2, 'line 2'), (3, 'line 3'), (1, 'line 4')]
将产生以下结果:
{'line 1': {'line 2': {'line 3': {}}}, 'line 4': {}, 'line 5': {}}
或者稍微复杂一点:
tuple_list = [(1, 'line 1'), (2, 'line 2'), (2, 'line 6'), (3, 'line 3'), (3, 'line 7'), (1, 'line 4'), (1, 'line 5')]
会屈服
{'line 1': {'line 2': {}, 'line 6': {'line 3': {}, 'line 7': {}}}, 'line 4': {}, 'line 5': {}}
由于您的级别不限于少数,因此仅通过普通 IF 来完成它不是一个好方法。 最好先构建一棵树,然后遍历树并创建您想要的表示。 这样做也很容易,您有多个根节点(其中 parent=None),每个根节点都有一个子节点列表,并且对子节点重复此操作,因此您有一个树。 您现在从根开始并进行所需的排序!
它很容易实现,我想你明白了!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.