【问题标题】:How to create nested dictionary with process IDs in python如何在python中创建带有进程ID的嵌套字典
【发布时间】:2020-09-09 00:39:05
【问题描述】:

我正在尝试创建一个进程树。我有 .csv 文件,其中两列采用这种父子格式。未设置行数。我想创建一个格式为{Parent : {Child : {}, Child: {}}} 的嵌套字典,其中父键具有其子级的字典作为值,而这些子级具有其子级的字典。

这就是输入的具体内容:

  • [PPID,PID]
  • [PPID,PID]
  • [PPID,PID]
  • [PPID,PID]
  • ...等

我在这里找到了递归解决方案:Create a nested dictionary using recursion Python

def split(data):
  if len(data) == 0:
      return data #trivial case, we have no element therefore we return empty list
  else: #if we have elements
      first_value = data[0] #we take the first value
      data = {first_value : split(data[1:])} #data[1:] will return a list with every value but the first value
      return data #this is called after the last recursion is called

但是,这似乎对我不起作用,因为它只会为父母显示一个孩子。我一直在寻找,但找不到方法。

【问题讨论】:

  • 您是否在寻找最佳解决方案(时间和/或空间)?我可以立即想到的一种方法是遍历数据一次以获取字典的键,然后再次迭代以获取每个键的直接子项(这将为您提供邻接列表)。在此之后,初始化第二个字典,并且对于第一个字典中的每个键,使用 DFS 遵循从父节点开始并在父节点的每个子节点结束的路径。在您的第二本词典中保留这些路径的副本。完成后,第二本词典就是您要查找的内容。
  • 转换字典列表(id-parent)看:stackoverflow.com/a/71555459/15392974

标签: python dictionary tree nested


【解决方案1】:

您可以使用多种算法来构建此树。正确的路径将取决于时间/空间复杂度。

对于这类问题,我通常的首选解决方案通常是使用简单的循环和递归,并在此基础上不断发展。比如:

def build_pid_tree(pid_list, root_pid, result=None):
    if result is None:
        result = {}

    if root_pid not in result:
        result[root_pid] = {}

    for (ppid, pid,) in pid_list:
        if ppid != root_pid:
            continue

        if pid not in result[ppid]:
            result[ppid][pid] = {}

        build_pid_tree(pid_list, pid, result[ppid])

    return result

【讨论】:

  • 嗨 Gustavo,我不知道我是否做错了什么,但我并没有完全得到结果。我理解这段代码是如何工作的。但是,当我运行它时,循环会提前结束,并且只给我一个包含三个节点的字典,例如 {PPID : {PID : {PID : {} } } }。第三个节点是叶子,当它返回时,我假设循环应该继续,但它会再次返回,直到整个函数结束。
  • 应该是这种情况(here's my running example。你介意分享你正在尝试的测试数据吗?
猜你喜欢
  • 1970-01-01
  • 2022-11-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-26
  • 2023-01-18
  • 1970-01-01
  • 1970-01-01
  • 2018-01-11
相关资源
最近更新 更多