给定(父,子)的平面列表,创建分层字典树

Dim*_*iop 2 python dictionary python-3.x

我有一个包含名称的元组列表.这些名称是父名和子名,我想创建一个带有名称的分层字典树.例如,我有以下列表:

[('john','marry'),('mike','john'),('mike','hellen'),('john','elisa')]
Run Code Online (Sandbox Code Playgroud)

我想创建这个:

{
    'mike':{
        'john':{
            'marry':{}
            'elisa':{}
         }
         'hellen':{}
        }
}
Run Code Online (Sandbox Code Playgroud)

MSe*_*ert 9

假设它表现良好(没有周期,没有重复的名字或一个孩子的多个父母),你可以简单地使用"有向图"并遍历它.为了找到根,我还使用了一个字典,其中包含一个布尔值,指示该名称是否有任何父级:

lst = [('john','marry'), ('mike','john'), ('mike','hellen'), ('john','elisa')]

# Build a directed graph and a list of all names that have no parent
graph = {name: set() for tup in lst for name in tup}
has_parent = {name: False for tup in lst for name in tup}
for parent, child in lst:
    graph[parent].add(child)
    has_parent[child] = True

# All names that have absolutely no parent:
roots = [name for name, parents in has_parent.items() if not parents]

# traversal of the graph (doesn't care about duplicates and cycles)
def traverse(hierarchy, graph, names):
    for name in names:
        hierarchy[name] = traverse({}, graph, graph[name])
    return hierarchy

traverse({}, graph, roots)
# {'mike': {'hellen': {}, 'john': {'elisa': {}, 'marry': {}}}}
Run Code Online (Sandbox Code Playgroud)