首页 文章

Python NetworkX - 从嵌套字典中获取DiGraph

提问于
浏览
0

我试图从嵌套字典在python的NetworkX中创建一个简单的DiGraph,但它看起来像内置初始化并没有构建最终的叶节点 .

玩具示例:

class_hierarchy= {-1: ["A", "B"], 
"A":{"A1":[1], "A2":[3,4]}, 
"B": {"B1":[5,6], "B2": [7,8]}}

建筑图:

G = DiGraph(class_hierarchy)

现在让我们看看它们里面有什么:

G.nodes
Out[86]: NodeView((-1, 'A', 'B', 'A1', 'A2', 'B1', 'B2'))

看起来没有添加最终节点

检查一下:

list(G.successors('A'))
Out[88]: ['A1', 'A2']

看起来很合理

但:

list(G.successors('A1'))
Out[89]: []

我不确定为什么会这样? Documentation for NetworkX指定:

incoming_graph_data(输入图形(可选,默认:无)) - 初始化图形的数据 . 如果为None(默认),则创建一个空图 . 数据可以是to_networkx_graph()函数支持的任何格式,目前包括边列表, dict of dicts ,列表字典等...

知道我做错了什么吗?

1 回答

  • 1

    你有一个混合输入,它既是 dict of lists 又是 dict of dicts . Networkx 会将其解释为 dict of lists .
    请参阅following code,其中 dataclass_hierarchy .

    if isinstance(data, dict):
            try:
                #this will raise an exception
                return from_dict_of_dicts(data, create_using=create_using,
                                      multigraph_input=multigraph_input)
            except:
                try:
                    # this is what is called in your case
                    return from_dict_of_lists(data, create_using=create_using)
                except:
                    raise TypeError("Input is not known type.")
    

    在您的情况下, networkx 期望列表邻接表示 .
    例如,预期输入的格式为: key: value - > node u: list of nodes [v1,v2,...,vn] u is connected with (例如,{0:[1,2],1:[3,4]} .

    networkx对您输入的内容如下:

    G=nx.DiGraph()
    
    edges_list = [((node, nbr)) for node, nbrlist in d.items() for nbr in nbrlist]
    # [(-1, 'A'), (-1, 'B'), ('A', 'A1'), ('A', 'A2'), ('B', 'B1'), ('B', 'B2')]
    
    G.add_edges_from(edges_list)
    

    因此,您必须根据您给出的含义更改格式 .

相关问题