从路径名制作树结构

Ada*_*da 6 python dictionary

这可能很简单,但我不确定在这里做什么。在 Python 中,我想查看如下列表:

full_list = ["A/A/A", "A/A/B", "B/B/B", "A/C/B"]
Run Code Online (Sandbox Code Playgroud)

并根据这些标签获取具有一种树结构的字典,如下所示:

dictionary = {"A:{"A":["A", "B"], "C":["B"]},"B":{"B":["B]}} 
Run Code Online (Sandbox Code Playgroud)

但我不知道该怎么做。我意识到我需要一些嵌套的 for 循环。我知道 Python 中的 split() 函数。

Aja*_*234 2

您可以使用递归collections.defaultdict

from collections import defaultdict
def to_tree(data):
   d = defaultdict(list)
   for a, *b in data:
      d[a].append(b)
   return {a:[i for [i] in b] if all(len(i) == 1 for i in b) else to_tree(b)  
           for a, b in d.items()}

full_list = ["A/A/A", "A/A/B", "B/B/B", "A/C/B"]
result = to_tree([i.split('/') for i in full_list])
Run Code Online (Sandbox Code Playgroud)

输出:

{'A': {'A': ['A', 'B'], 'C': ['B']}, 'B': {'B': ['B']}}
Run Code Online (Sandbox Code Playgroud)